(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';

var _ref;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _app = require('./app');

require('./dx-ext');

require('./qrcode');

require('./order');

require('./data');

require('./product');

require('./daily');

require('./dealer');

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

jQuery.extend({
	crudStoreResp: null,

	crudStore: function crudStore(url, options) {

		var SERVICE_URL = url;
		options = $.extend({
			onDataArrived: function onDataArrived(data) {
				return data;
			}
		}, options);

		return new DevExpress.data.CustomStore($.extend({}, options, {

			load: function load(loadOptions) {

				var u = new Url(SERVICE_URL);

				u.query._param = JSON.stringify(loadOptions);

				return $.getJSON(u).then(function (resp) {
					console.log("data done");
					return options.onDataArrived(resp);
				});
			},

			byKey: function byKey(key) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.getJSON(u).then(function (resp) {
					return resp.data;
				});
			},

			insert: function insert(values) {
				return $.post(SERVICE_URL, values).always(function (resp) {
					$.crudStoreResp = resp.responseJSON;
					return resp;
				});
			},

			update: function update(key, values) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.ajax({
					url: u,
					method: "PUT",
					data: values
				}).always(function (resp) {
					$.crudStoreResp = resp.responseJSON;
					return resp;
				});
			},

			remove: function remove(key) {
				var u = new Url(SERVICE_URL);
				u.path += "/" + encodeURIComponent(key);

				return $.ajax({
					url: u,
					method: "DELETE"
				});
			}

		}));
	},

	crud: function crud(options) {
		if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
			var initCrudForm = function initCrudForm($c, context) {
				var id = context.params.id,
				    formOptions = {
					readOnly: false,
					showColonAfterLabel: true,
					showValidationSummary: false,
					colCount: 1,
					validationGroup: "crud",
					items: [],
					onFieldDataChanged: function onFieldDataChanged(e) {
						// console.log("onFieldDataChanged");
						// console.log(e);
					}
				};

				if (id) {
					formOptions.onContentReady = function (e) {
						store.byKey(id).then(function (resp) {

							if (options.form.beforeDataUpdate) {
								options.form.beforeDataUpdate(form, {
									data: resp
								});
							}
							e.component.option('formData', resp);

							if (options.form.afterDataUpdate) {
								options.form.afterDataUpdate(form, {
									data: resp
								});
							}
						});
					};
				}

				var items = [];
				if (options.form && options.form.items) {
					var scene = id ? 'edit' : 'create';
					$.each(options.form.items, function (i, item) {
						if (item.scene && $.inArray(scene, item.scene) < 0) {} else {
							items.push(item);
						}
					});
				}

				var form = $("#form", $c).dxForm($.extend(formOptions, options.form, {
					items: items
				})).dxForm('instance');

				$("#form-container #save", $c).click(function () {
					var result = form.validate();

					if (!result.isValid) {
						var $el = result.validators[0].element();

						var offset = $el.offset();

						$('html, body').animate({
							scrollTop: offset.top - $("header.app-header").height() - 20
						});
					} else {
						$("#form-container", $c).submit();
					}

					return false;
				});

				$("#form-container", $c).on("submit", function (e) {
					var bs = true;
					if (options.form.beforeSubmit) {
						bs = options.form.beforeSubmit(form, id);
					}

					$.when(bs).then(function (result) {
						if (result) {
							if (id) {
								store.update(id, form.option('formData')).then(function (values, resp) {
									DevExpress.ui.notify({
										message: "已更新"
									}, "success", 1000);
									if (options.form.onSaved) {
										options.form.onSaved.call(context, values, resp);
									} else {
										context.redirect('#/' + route);
									}
								}).fail(function () {
									DevExpress.ui.notify({
										message: $.crudStoreResp.message
									}, "warning", 2000);
								});
							} else {
								store.insert(form.option('formData')).then(function (values, resp) {
									if (resp.status == "error") {
										DevExpress.ui.dialog.alert(resp.msg, '提示');
										return false;
									} else {
										DevExpress.ui.notify({
											message: "已完成"
										}, "success", 1000);
										context.redirect('#/' + route);
										//		        						context.redirect('#/' + route + '/edit/' + resp.model.id);
									}
								}).fail(function (resp) {
									DevExpress.ui.notify({
										message: resp
									}, "warning", 2000);
								});
							}
						}
					});

					return false;
				});

				$("#form-container .delete", $c).click(function () {
					DevExpress.ui.dialog.confirm("确认删除吗?", "请确认").done(function (dialogResult) {
						if (dialogResult) {

							store.remove(id).then(function (resp) {

								DevExpress.ui.notify({
									message: "已删除"
								}, "success", 1000);
								context.redirect("#/" + route);
							});
						}
					});

					return false;
				});

				$("#form-container #cancel").click(function () {
					context.redirect("#/" + route);
					return false;
				});

				var saveNext = false;
				$("#form-container #save").click(function () {
					saveNext = false;
					return false;
				});
				$("#form-container #save-next").click(function () {
					saveNext = true;
					return false;
				});
			};

			// create or edit
			//			console.log("add crud " + route + "/edit");

			var app = options.app,
			    route = options.route,
			    store = jQuery.crudStore(options.url || API(route), options.store);

			options.search = $.extend({
				mobile: 'mobile',
				name: 'uname',
				dateA: 'dateA'
			}, options.search);

			// list

			app.get('#/' + route, function () {
				var eventContext = this,
				    capable = $.extend({
					create: true
				}, options.capable);
				$('#content').html(Mustache.render($("#crud-list").html(), $.extend({}, options, {
					capable: capable
				}))).dxInit();

				var gridType = options.gridType || "dxDataGrid";

				if (options.buttons) {
					$.each(options.buttons, function (i, button) {
						button.instance = $("<div>").dxButton($.extend({
							type: 'normal',
							onClick: function onClick(e) {
								var selections = [];

								if (options.onGetSelectedRowsData) {
									selections = options.onGetSelectedRowsData.call(eventContext, $("#content .crud-grid"));
								} else if (!options.onRenderGrid) {
									selections = $("#content .crud-grid")[gridType]('getSelectedRowsData');
								}

								button.onRoute && button.onRoute.call(eventContext, e.component, selections);
							}
						}, button)).appendTo($("#content .crud-buttons")).dxButton('instance');
					});
				}

				var defaultToolbarItems = [];
				if (options.capable.create) {
					defaultToolbarItems.push('create');
				}

				var toolbarOptions = options.toolbar ? options.toolbar : {
					items: defaultToolbarItems
				};

				$.each(toolbarOptions.items, function (i, item) {
					if (item === 'create') {
						toolbarOptions.items[i] = {
							location: 'before',
							widget: 'dxButton',
							options: {
								text: '新建',
								onClick: function onClick() {
									eventContext.redirect('#/' + route + '/edit');
								}
							}
						};
					}
				});

				console.log(toolbarOptions);
				$("#content .toolbar").dxToolbar(toolbarOptions);

				var ds = new DevExpress.data.DataSource({
					store: store
				});

				if (eventContext.params) {
					$.each(eventContext.params, function (k, v) {
						if (typeof v !== 'function' && (typeof v === 'undefined' ? 'undefined' : _typeof(v)) !== 'object') {
							ds.filter(k, '=', v);
						}
					});
				}

				var param = {
					dataSource: ds,
					allowColumnResizing: true,
					selection: {
						mode: "multiple",
						showCheckBoxesMode: 'always',
						selectAllMode: 'page'
					},
					remoteOperations: true,
					paging: {
						pageSize: 10,
						pageIndex: 0
					},
					onSelectionChanged: function onSelectionChanged(e) {
						$.each(options.buttons, function (i, button) {
							button.onSelectionChanged && button.onSelectionChanged.call(eventContext, button.instance, e.selectedRowsData, e.component);
						});
					}
				};

				if (options.columns) {
					for (var i = 0; i < options.columns.length; i++) {
						if (options.columns[i].buttons) {

							options.columns[i].cellTemplate = function (buttons) {
								return function (container, ei) {

									$.each(buttons, function (i, button) {
										var title = button.title,
										    url = '#';

										if (button.url) {
											url = Mustache.render(button.url, ei.data);
										}

										var el = $(Mustache.render('<a style="margin: 0 10px;" href="{{url}}">{{title}}</a>', {
											title: title,
											url: url
										}));

										if (button.onClick) {
											el.click(function () {

												button.onClick(ei.data, ei.component);
												return false;
											});
										}

										el.appendTo(container);

										if (button.del) {

											$("<span style='margin:0 5px;vertical-align:1px'>|</span>").appendTo(container);

											$("<a>").text("删除").click(function () {

												DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function (sele) {

													if (sele) {
														var getId = ei.data.id;

														$.ajax({
															type: "delete",
															url: $.config('apiUrl') + "restful/" + getId + "?_model=" + button.del
														}).then(function (a) {

															if (a.status = "success") {

																DevExpress.ui.notify({
																	message: function message() {

																		var gridComponent = $("#content .crud-grid").dxDataGrid('instance');

																		gridComponent.option('dataSource').load();

																		return "成功删除";
																	}
																}, "success", 1000);
															} else {

																DevExpress.ui.notify({

																	message: function message() {

																		return "操作失败";
																	}
																}, "warning", 1000);
															}
														});
													}
												});
											}).appendTo(container);
										}
									});
								};
							}(options.columns[i].buttons);
						}
					}
					param['columns'] = options.columns;
				}

				if (options.onRenderGrid) {
					options.onRenderGrid.call(eventContext, $("#content .crud-grid"), $.extend({}, param, options.grid));
				} else {
					$("#content .crud-grid")[gridType]($.extend({}, param, options.grid));
				};

				// var gridInst = $("#content .crud-grid")[gridType]("instance");

				if (!options.search['mobile']) $("#content [data-search=mobile]").closest(".input-group").hide();
				if (!options.search['name']) $("#content [data-search=name]").closest(".input-group").hide();
				if (!options.search['lookup']) $("#content [data-search=lookup]").closest(".lookup").hide();
				if (!options.search['mobile'] && !options.search['name']) {
					$("#content .grid-search").hide();
				}

				var now = new Date();
				$("#date").dxDateBox({
					type: "date",
					value: now,
					displayFormat: 'yyyy-MM-dd',
					dateSerializationFormat: "yyyy-MM-dd",
					editorOptions: {
						displayFormat: 'yyyy-MM-dd',
						dateSerializationFormat: 'yyyy-MM-dd'
					}
				});

				$("#content .grid-search").click(function () {
					var name = $("#content [data-search=name]").val(),
					    mobile = $("#content [data-search=mobile]").val(),
					    dateA = $("#content #date").dxDateBox('option', 'value');

					if (name) {
						ds.searchExpr(options.search['name']);
						$("#content [data-search=mobile]").val('');
					} else if (mobile) {
						ds.searchExpr(options.search['mobile']);
						$("#content [data-search=name]").val('');
					} else if (dateA) {
						ds.searchExpr(options.search['dateA']);
						$("#content #date").dxDateBox('option', 'value');
					}

					ds.searchOperation("contains");
					ds.searchValue(name || mobile || dateA);
					ds.reload();
				});

				// $("#modify_pwd", $(this)).dxDataGrid(param);
			});

			app.get('#/' + route + "/edit", function () {
				var eventContext = this,
				    capable = $.extend({
					saveNext: true
				}, options.capable);
				$('#content').html(Mustache.render($("#crud-form").html(), $.extend({}, options, {
					capable: capable,
					role: '新建'
				}))).dxInit();

				initCrudForm($("#content"), this);
			});

			//			console.log("add crud " + route + "/edit/:id");

			app.get('#/' + route + "/edit/:id", function () {
				var eventContext = this,
				    capable = $.extend({
					delete: true
				}, options.capable);
				$('#content').html(Mustache.render($("#crud-form").html(), $.extend({}, options, {
					capable: capable,
					role: '编辑'
				}))).dxInit();

				initCrudForm($("#content"), this);
			});
		}
	},

	dxCall: function dxCall() {
		var comp = $(this).data('dxComponents');
		if (comp && comp.length) {
			var inst = $(this)[comp[0]]("instance");

			return inst[arguments[0]].apply(inst, arguments.slice(1));
		} else {
			return undefined;
		}
	}
});

_app.App.registerCrud({
	route: 'product',
	url: API('restful?_model=product'),
	title: '产品',
	placeholder: '产品名称',
	capable: {
		create: true
	},
	grid: {
		selection: {
			mode: 'none'
		},
		columnAutoWidth: true,
		showRowLines: true,
		wordWrapEnabled: true
	},
	toolbar: {
		items: [{
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '新建',
				onClick: function onClick() {
					_app.App.getEventContext().redirect('#/product/edit');
				}
			}
		}]
	},
	search: {
		name: 'chname'
	},
	columns: [{
		dataField: 'id',
		caption: 'id'
	}, {
		dataField: 'chname',
		caption: '产品名称'
	}, {
		dataField: 'weight',
		caption: '权重',
		cellTemplate: function cellTemplate(con, da) {
			$(con).dxWeight("product", da);
		}
	}, {
		dataField: 'online',
		caption: '上下线',
		cellTemplate: function cellTemplate(con, opt) {
			$(con).dxUpdown('product', opt);
		}
	}, {
		minWidth: 100,
		caption: '操作',
		buttons: [{
			title: '编辑',
			// url: '#/newproduct/{{id}}',
			url: '#/product/edit/{{id}}',
			del: 'product'
		}]

	}, (_ref = {
		caption: 'id'
	}, _defineProperty(_ref, 'caption', "产品价格"), _defineProperty(_ref, 'buttons', [{
		title: "查看",
		url: '#/price?id={{id}}'

	}]), _ref), {
		dataField: 'pv',
		caption: 'pv'
	}, {
		dataField: 'uv',
		caption: 'uv'
	}, {
		dataField: 'collect_count',
		caption: '收藏量'
	}, {
		dataField: 'order_count',
		minWidth: 100,
		caption: '订单量'
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		beforeSubmit: function beforeSubmit(form, id) {
			var formData = form.option('formData');
			formData.is_hot = formData.is_hot ? 1 : 0;
			form.option('formData', formData);
			return true;
		},
		colCount: 1,
		items: [{
			itemType: "group",
			items: [{
				dataField: "chname",
				label: {
					text: '产品名称'
				},
				validationRules: [{
					type: "required",
					message: "请输入产品名称"
				}]
			}, {
				dataField: 'attr_group_id',
				label: { text: '产品属性' },
				editorType: 'dxSelectBox',
				editorOptions: {
					dataSource: $.crudStore(API('restful?_model=product-attr-group')),
					valueExpr: 'id',
					searchEnabled: true,
					displayExpr: 'name'
				}
			}, {
				dataField: 'category_id',
				label: { text: '分类' },
				editorType: 'dxSelectBox',
				editorOptions: {
					dataSource: [{ name: '车载', id: 1 }, { name: '家用', id: 2 }],
					placeholder: "分类",
					searchEnabled: true,
					valueExpr: 'id',
					displayExpr: 'name',
					noDataText: '没有请求到分类数据',
					deferRendering: false,
					itemTemplate: function itemTemplate(data) {
						return data.name;
					}
				}
			}, {
				dataField: "is_hot",
				label: { text: '设置热销' },
				editorType: 'dxCheckBox'
			}, {
				dataField: 'banner',
				label: { text: '列表图' },
				editorType: 'imagesdetail',
				editorOptions: {
					single: true
				}
			}, {
				dataField: 'covers',
				label: { text: '详情轮播图' },
				editorType: 'imagesdetail'
			}, {
				dataField: 'detail',
				label: { text: '产品详情' },
				editorType: 'imagesdetail'
			}, {
				dataField: 'param',
				label: { text: '产品参数' },
				editorType: 'imagesdetail'
			}]
		}]
	}

});

var user_search_name = '';

_app.App.registerCrud({
	url: API('restful?_model=user'),
	route: 'user_list',
	title: '用户',
	capable: {
		create: false,
		delete: false
	},
	search: {
		mobile: 'mobile',
		name: 'name'
	},
	toolbar: {
		items: [{
			location: 'before',
			widget: 'dxTextBox',
			options: {
				width: 300,
				placeholder: '请输入用户姓名或手机号',
				onInitialized: function onInitialized(e) {
					user_search_name = e.component;
				}
			}
		}, {
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '搜索用户',
				onClick: function onClick() {
					var ds = _app.App.crudGridInstance().option('dataSource');

					ds.searchExpr(['name', 'mobile']);
					ds.searchValue(user_search_name.option('value'));

					ds.reload();
				}
			}
		}]
	},
	grid: {
		selection: {
			mode: 'none'
		}
	},
	columns: [{
		dataField: 'id',
		caption: 'id',
		width: 80
	}, {
		dataField: 'name',
		caption: '姓名',
		width: 200
	}, {
		dataField: 'mobile',
		caption: '联系方式',
		width: 150
	}, {
		dataField: 'bonus_total',
		caption: '总分红'
	}, {
		dataField: 'parent_name',
		caption: '邀请人'
	}, {
		dataField: 'order_count',
		caption: '产品购买次数'
	}, {
		dataField: 'is_dealer',
		caption: '设置经销商',
		cellTemplate: function cellTemplate($c, d) {
			var ast = d.value,
			    state = 'active',
			    text = '设置经销商';
			if (ast) {
				state = 'stop';
				text = '取消经销商';
			}
			$('<a>').click(function () {

				$.ajax({
					url: API('dealer/change'),
					type: 'post',
					data: { userIds: d.row.data.id, state: state },
					headers: { 'Authorization': "bearer " + localStorage.accessToken },
					success: function success(res) {
						if (res.data.success === 0) {
							DevExpress.ui.notify(res.data.errors[0], 'warning', 1500);
						} else {
							var ds = _app.App.crudGridInstance().option('dataSource');
							ds.reload();
							DevExpress.ui.notify(text + '操作成功', 'success', 1500);
						}
					},
					error: function error() {
						DevExpress.ui.notify('未知错误，请重试', 'warning', 1500);
						console.error('dealer/change');
					}
				});
			}).text(text).appendTo($c);
		}
	}]
});

var complete_list_filter = '';
_app.App.registerCrud({
	url: API('restful?_model=user-withdraw'),
	route: 'complete',
	title: '用户',
	capable: {
		create: false,
		delete: false
	},
	search: {
		mobile: 'mobile',
		name: 'name'
	},
	toolbar: {
		items: [{
			location: 'before',
			widget: 'dxTextBox',
			options: {
				width: 300,
				placeholder: '请输入用户姓名或手机号',
				onInitialized: function onInitialized(e) {
					complete_list_filter = e.component;
				}
			}
		}, {
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '搜索用户',
				onClick: function onClick() {
					var ds = _app.App.crudGridInstance().option('dataSource');
					ds.searchExpr(['username', 'mobile']);
					ds.searchValue(complete_list_filter.option('value'));
					ds.reload();
				}
			}
		}, {
			location: 'before',
			widget: 'dxSelectBox',
			options: {
				dataSource: [{ value: '', text: '所有' }, { value: 0, text: '待审核' }, { value: 1, text: '已审核' }, { value: 2, text: '已提现' }, { value: 3, text: '已拒绝' }],
				displayExpr: 'text',
				valueExpr: 'value',
				value: '',
				onValueChanged: function onValueChanged(e) {
					var ds = _app.App.crudGridInstance().option('dataSource');
					if (e.value || e.value === 0) {
						ds.filter(['state', '=', e.value]);
					} else {
						ds.filter(null);
					}

					ds.reload();
				}
			}
		}]
	},
	grid: {
		selection: {
			mode: 'none'
		}
	},
	columns: [{
		dataField: 'username',
		caption: '用户昵称',
		width: 200
	}, {
		dataField: 'mobile',
		caption: '联系方式',
		width: 150
	}, {
		dataField: 'request_time',
		caption: '请示时间'
	}, {
		dataField: 'card_bank',
		caption: '提现银行',
		cellTemplate: function cellTemplate($c, d) {
			var data = d.row.data;
			$('<div/>').text(data.card_bank).appendTo($c);
			$('<div/>').text(data.bank_subbranch_name).appendTo($c);
			$('<div/>').text(data.card_number).appendTo($c);
		}
	}, {
		dataField: 'card_username',
		caption: '帐号姓名'
	}, {
		dataField: 'request_amount',
		caption: '提现额度'
	}, {
		dataField: 'remark',
		caption: '备注'
	}, {
		dataField: 'state',
		caption: '状态',
		cellTemplate: function cellTemplate($c, d) {
			var text = '';
			switch (d.value) {
				case 0:
					text = '待审核';break;
				case 1:
					text = '已审核';break;
				case 2:
					text = '已提现';break;
				case 3:
					text = '已拒绝';break;
			}
			$c.text(text);
		}
	}, {
		dataField: "state",
		caption: '审核',
		cellTemplate: function cellTemplate($c, d) {
			function fa(state) {
				var remark = prompt('请输入备注');
				if (remark) {
					var data = {
						ids: d.row.data.id,
						remark: remark,
						state: state
					};
					$.ajax({
						url: API('withdraw/change'),
						data: data,
						method: "post",
						headers: {
							Authorization: "bearer " + localStorage.accessToken
						},
						success: function success(resp) {
							if (resp.status == 'success') {
								var ds = _app.App.crudGridInstance().option('dataSource');
								ds.reload();
								DevExpress.ui.notify('操作成功', 'success', 1500);
							} else {
								DevExpress.ui.notify('操作失败:' + resp.message, 'warning', 1500);
							}
						},
						error: function error(err) {
							DevExpress.ui.notify('操作失败', 'warning', 1500);
						}
					});
				}
			}
			if (d.value === 0) {
				$('<a/>').text('通过').click(function () {
					fa('pass');
				}).appendTo($c);

				$('<span/>').text(' | ').css('margin', '0 3px').appendTo($c);

				$('<span/>').text('拒绝').click(function () {
					fa('refuse');
				}).appendTo($c);
			}
		}
	}, {
		caption: '打款确认',
		dataField: "id",
		cellTemplate: function cellTemplate($c, d) {
			if (d.row.data.state === 1) {
				$('<a/>').text('确认打款').click(function () {
					if (confirm('是否确认打款')) {
						$.ajax({
							url: API('withdraw/complete'),
							data: { ids: d.value },
							method: "post",
							headers: {
								Authorization: "bearer " + localStorage.accessToken
							},
							success: function success(resp) {
								if (resp.status == 'success') {
									var ds = _app.App.crudGridInstance().option('dataSource');
									ds.reload();
									DevExpress.ui.notify('操作成功', 'success', 1500);
								} else {
									DevExpress.ui.notify('操作失败：' + resp.message, 'warning', 1500);
								}
							},
							error: function error(err) {
								DevExpress.ui.notify('操作失败', 'warning', 1500);
							}
						});
					}
				}).appendTo($c);
			}
		}
	}]
});

_app.App.registerCrud({
	url: API('restful?_model=sys-admin'),
	route: 'admin-users',
	title: '系统管理员',
	placeholder: '会员名',
	capable: {
		create: true
	},
	buttons: [{
		text: '删除',
		type: 'danger',
		disabled: true,
		onSelectionChanged: function onSelectionChanged(component, selections, gridComponent) {
			component.option('disabled', selections.length <= 0);
		},
		onClick: function onClick() {
			var store = $.crudStore(API("admin")),
			    gridComponent = $("#content .crud-grid").dxDataGrid('instance'),
			    selections = gridComponent.getSelectedRowsData(),
			    ids = $.map(selections, function (item) {
				return item.id;
			}).join(",");

			DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function (dialogResult) {
				if (dialogResult) {
					store.remove(ids).then(function (resp) {

						DevExpress.ui.notify({
							message: "已删除"
						}, "success", 1000);
						gridComponent.option('dataSource').load();
					});
				}
			});
			return false;
		}
	}],
	columns: [{
		dataField: 'name',
		caption: '名称'
	}, {
		dataField: 'account',
		caption: '账号'
	}, {
		dataField: 'userType',
		caption: '权限',
		cellTemplate: function cellTemplate($c, d) {

			var text = '';
			if (d.value == 'admin') {
				text = '管理员';
			} else if (d.value == 'editor') {
				text = '录入员';
			};
			$c.text(text);
		}
	}, {
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		caption: '操作',
		buttons: [{
			title: '编辑',
			url: '#/admin-users/edit/{{id}}'
		}, {
			title: '更改密码',
			url: '#/admin-users/password/edit/{{id}}'
		}, {
			title: '删除',
			onClick: function onClick(data) {
				DevExpress.ui.dialog.confirm("确定删除 " + data.account + " 吗?", "请确认").done(function (dialogResult) {
					if (dialogResult) {
						var ds = _app.App.crudGridInstance().option('dataSource');
						ds.store().remove(data.id).then(function (resp) {
							DevExpress.ui.notify({
								message: "已删除"
							}, "success", 1000);
							ds.reload();
						});
					}
				});
			}
		}]
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		items: [{
			dataField: 'name',
			label: {
				text: '名称'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'account',
			label: {
				text: '帐号'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			scene: ['create'],
			dataField: 'password',
			label: {
				text: '密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			scene: ['create'],
			dataField: 'password_confirmation',
			label: {
				text: '确认密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'userType',
			editorType: 'dxSelectBox',
			label: { text: '权限' },
			validationRules: [{
				type: "required"
			}],
			editorOptions: {
				dataSource: [{ name: '管理员', value: 'admin' }, { name: '产品录入员', value: 'editor' }],
				displayExpr: 'name',
				valueExpr: "value",
				onValueChanged: function onValueChanged(e) {
					_app.App.getFormInstance().option('formData.userType', e.value);
				}
			}
		}, {
			label: {
				text: '允许访问ip段'
			}
		}, {
			dataField: 'ip_min',
			label: {
				text: '最小值'
			}
		}, {
			dataField: 'ip_max',
			label: {
				text: '最大值'
			}
		}]
	}
});

_app.App.registerCrud({
	url: API('restful?_model=sys-admin'),
	route: 'admin-users/password',
	title: '更改密码',
	capable: {
		create: false,
		delete: false
	},
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		onSaved: function onSaved() {
			this.redirect("#/admin-users");
		},
		items: [{
			dataField: 'name',
			label: {
				text: '用户名'
			},
			validationRules: [{
				type: "required"
			}],
			editorOptions: {
				readOnly: true
			}
		}, {
			dataField: 'account',
			label: {
				text: '帐号'
			},
			validationRules: [{
				type: "required"
			}],
			editorOptions: {
				readOnly: true
			}
		}, {
			dataField: 'password',
			label: {
				text: '密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'password_confirmation',
			label: {
				text: '确认密码'
			},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}]
	}
});

_app.App.registerCrud({
	url: API('restful?_model=focus-picture'),
	route: 'banner',
	title: '焦点图',
	capable: {
		create: true
	},
	buttons: [],
	columns: [{
		dataField: 'pic',
		caption: '图片',
		cellTemplate: function cellTemplate(c, ci) {
			$("<img src='" + ci.data.pic + "?imageView2/0/h/60'/>").appendTo(c);
		}
	}, {
		dataField: 'created_at',
		caption: '创建时间'
	}, {
		dataField: 'title',
		caption: '标题'
	}, {
		dataField: 'type',
		caption: '类型',
		cellTemplate: function cellTemplate(c, ci) {
			c.html(ci.data.type === 'article' ? '其他' : '产品');
		}
	}, {
		dataField: 'weight',
		caption: '权重',
		cellTemplate: function cellTemplate(con, da) {
			$(con).dxWeight("focus", da);
		}
	}, {
		caption: '操作',
		cellTemplate: function cellTemplate(con, dat) {
			$("<a href='#' style='padding-right: 10px;'>编辑</a>").click(function () {
				_app.App.getEventContext().redirect('#/banner/edit/' + dat.data.id);
				return false;
			}).appendTo($(con));

			$(con).dxDelete('focus-picture', dat);
		}
	}],
	form: {
		beforeDataUpdate: function beforeDataUpdate(formInstance, e) {
			e.data.obj_id = parseInt(e.data.obj_id);
		},
		items: [{
			dataField: 'title',
			label: {
				text: '标题'
			},
			editorType: 'dxTextBox',
			editorOptions: {},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'pic',
			label: {
				text: '封面图片'
			},
			editorType: 'ImageUploader',
			editorOptions: {
				single: true,
				imageWidth: 750,
				imageHeight: 608
			},
			validationRules: [{
				type: "required"
			}]
		}, {
			dataField: 'type',
			label: {
				text: '类型'
			},
			validationRules: [{
				type: "required"
			}],
			editorType: 'dxRadioGroup',
			editorOptions: {
				layout: "horizontal",
				valueExpr: 'value',
				dataSource: [{
					text: '其他',
					value: 'article'
				}, {
					text: '产品',
					value: 'product'
				}],
				onValueChanged: function onValueChanged(e) {
					var formInstance = _app.App.getFormInstance();

					// formInstance.updateData({obj_id: 0});

					if (e.value === 'article') {
						formInstance.getEditor('obj_id').option({
							dataSource: $.crudStore(API('restful?_model=cms-article'))
						});
					} else {
						formInstance.getEditor('obj_id').option({
							dataSource: $.crudStore(API('restful?_model=wine-product'))
						});
					}
				}
			}
		}, {
			dataField: 'obj_id',
			label: {
				text: '产品'
			},
			validationRules: [{
				type: "required"
			}],
			editorType: 'dxSelectBox',
			editorOptions: {
				dataSource: $.crudStore(API('restful?_model=product')),
				showClearButton: true,
				searchEnabled: true,
				valueExpr: 'id',
				noDataText: '没有请求到数据',
				itemTemplate: function itemTemplate(data, index, $el) {
					if (data && data.chname && data.name) {
						$("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
					} else if (data && data.title) {
						$("<span>" + data.title + "</span>").appendTo($el);
					}
				},
				displayExpr: function displayExpr(data) {
					if (data && data.chname && data.name) {
						return data.chname + " (" + data.name + ")";
					} else if (data && data.title) {
						return data.title;
					} else {
						return "";
					}
				}
			}
		}]
	}
});

$(function () {

	var initApp = function initApp() {
		var app = $.sammy('#content', function () {
			var app = this;

			console.log("handle routes");
			console.log(_app.App.routes);

			$.each(_app.App.routes, function (i, route) {
				var m = route.name.match(/[^\/]*/);
				app.get('#/' + route.name, function () {

					var eventContext = this;

					route.onLoad && route.onLoad.call(route, eventContext, $('#content'));

					// $.get('template/' + m[0] + '.html', function(resp) {
					//  $('#content').html(resp).dxInit();
					//  $("#content").trigger("route.loaded", [eventContext])
					// });
				});
			});

			// for(var i = 0; i < routes.length; i++) {
			//  (function(route) {
			//      var m = route.match(/[^\/]*/);
			//      app.get('#/' + route, function() {

			//          var eventContext = this;

			//          $.get('template/' + m[0] + '.html', function(resp) {
			//              $('#content').html(resp).dxInit();
			//              $("#content").trigger("route.loaded", [eventContext])
			//          });
			//      });
			//  })(routes[i]);
			// }

			console.log("handle pages");
			console.log(_app.App.pages);
			$.each(_app.App.pages, function (i, page) {
				$.crud($.extend({
					app: app
				}, page));
			});
		});

		app.bind('changed', {}, function () {
			_app.App.setEventContext(this);
		});
		app.run('#/product');
	};

	if (!localStorage.accessToken) {
		window.location.href = 'login.html';
		return;
	} else {
		$.ajax({
			headers: {
				Authorization: "bearer " + localStorage.accessToken
			},
			url: API('auth/me'),
			type: 'get',
			success: function success(resp) {
				$(".app").show();

				var data = resp.data,
				    type = data.userType;
				// if (data.userType === 'super' && data.account === 'admin') {
				// 	type = 'super';
				// }
				_app.App.login(data);
				console.log(resp);
				$(".admin-name").text(data.name);
				$(".auth-" + type).show();

				initApp();
			},
			error: function error(resp) {
				window.location.href = 'login.html';
			}
		});
	}

	DevExpress.viz.currentTheme("generic.light");

	$("body").dxInit();
});


},{"./app":2,"./daily":3,"./data":4,"./dealer":5,"./dx-ext":6,"./order":7,"./product":9,"./qrcode":10}],2:[function(require,module,exports){
"use strict";

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var AppClass = function () {
	function AppClass() {
		_classCallCheck(this, AppClass);

		this._eventContext = null;
		this._loadingPanel = null;
		this._pages = [];
		this._routes = [];
		this._user = null;

		console.log("Making App");
	}

	_createClass(AppClass, [{
		key: "login",
		value: function login(user) {
			this._user = $.extend({}, user);
		}
	}, {
		key: "crudChartInstance",
		value: function crudChartInstance() {
			return $(".data-chart").dxChart("instance");
		}
	}, {
		key: "crudGridInstance",
		value: function crudGridInstance() {
			return $(".crud-grid").dxDataGrid("instance");
		}
	}, {
		key: "getFormInstance",
		value: function getFormInstance() {
			return $("#form").dxForm("instance");
		}
	}, {
		key: "getEventContext",
		value: function getEventContext() {
			return this._eventContext;
		}
	}, {
		key: "setEventContext",
		value: function setEventContext(v) {
			this._eventContext = v;
		}
	}, {
		key: "showLoading",
		value: function showLoading(message) {
			message = message || '正在加载...';

			this._loadingPanel = $("#loadpanel").dxLoadPanel({
				shadingColor: "rgba(0,0,0,0.4)",
				position: { of: "body" },
				visible: true,
				showIndicator: true,
				showPane: true,
				shading: true,
				closeOnOutsideClick: false,
				message: message
			}).dxLoadPanel("instance");
		}
	}, {
		key: "hideLoading",
		value: function hideLoading() {
			if (this._loadingPanel !== null) {
				this._loadingPanel.hide();
				this._loadingPanel = null;
			}
		}
	}, {
		key: "registerCrud",
		value: function registerCrud(opt) {
			this.pages.push(opt);
		}
	}, {
		key: "registerRoute",
		value: function registerRoute(opt) {
			this.routes.push(opt);
		}
	}, {
		key: "pages",
		get: function get() {
			return this._pages;
		}
	}, {
		key: "routes",
		get: function get() {
			return this._routes;
		}
	}, {
		key: "user",
		get: function get() {
			return this._user;
		}
	}]);

	return AppClass;
}();

var App = exports.App = new AppClass();


},{}],3:[function(require,module,exports){
'use strict';

var _app = require('./app');

var _util = require('./util');

var _util2 = _interopRequireDefault(_util);

var _page = require('./page');

require('./dx-ext');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// App.registerCrud({
// 	route: 'daily-sign',
// 	url: $.config('apiUrl') + 'restful?_model=cms-daily-sign',
// 	placeholder: '每日签',
// 	title: '每日签',
// 	capable: {
// 		create: true
// 	},
// 	search: {
// 		mobile: 'title',
// 	},
// 	columns: [{
// 			dataField: 'id',
// 			caption: 'id'
// 		}, {
// 			dataField: 'title',
// 			caption: '名称'
// 		}, {
// 			dataField: 'online_at',
// 			caption: '上线时间'
// 		}, {
// 			dataField: 'column_name',
// 			caption: '类别'
// 		}, {
// 			dataField: 'online',
// 			caption: '上下线',
// 			cellTemplate: function(con, data) {
// 				$(con).dxUpdown('article', data)
// 			}
// 		},
// 		{
// 			caption: '操作',
// 			buttons: [{
// 				title: '编辑',
// 				url: '#/daily-sign/edit/{{id}}',
// 				del: 'cms-daily-sign'
// 			}]
// 		}
// 	],
// 	form: {
// 		readOnly: false,
// 		showColonAfterLabel: true,
// 		showValidationSummary: false,
// 		colCount: 1,
// 		afterDataUpdate: function(formInstance, data) {
// 			//console.log(formInstance.geiEditor("#editor"));

// 		},
// 		beforeSubmit: function(form, id) {
// 			var formData = form.option('formData');
// 			var cover = [];
// 			$.each(formData.covers, function(i, cov) {
// 				cover.push(cov.id)
// 			});
// 			if(cover.length == 0) {
// 				formData.covers_ids = 0;
// 			} else {
// 				formData.cover_ids = cover.join()
// 			};
// 			formData.column_id = "1";
// 			formData.covers = "";
// 			formData.state = "publish";
// 			form.option('formData', formData);
// 			return true;
// 		},
// 		items: [{
// 			itemType: "group",

// 			items: [{
// 				dataField: "title",
// 				label: {
// 					text: '文章名称'
// 				},
// 				validationRules: [{
// 					type: "required",
// 					message: "请输入名称"
// 				}]
// 			},
// 			{
// 				dataField: "content",
// 				label: {
// 					text: '文章内容'
// 				},
// 				editorType: 'dxTextArea',
// 				validationRules: [{
// 					type: "required",
// 					message: "请输入内容"
// 				}]
// 			},
// 			{
// 				dataField: "covers",
// 				name: "name",
// 				validationRules: [{
// 					type: 'required'
// 				}],
// 				editorType: "ImageUploader",
// 				label: {
// 					text: '每日签图片'
// 				},
// 				editorOptions: {
// 					imageWidth: 690,
// 					imageHeight: 518
// 				}
// 			},
// 			{
// 				dataField: "online_at",
// 				label: {
// 					text: '上线日期'
// 				},
// 				editorType: "dxDateBox",
// 				editorOptions: {
// 					displayFormat: 'yyyy-MM-dd',
// 					dateSerializationFormat: 'yyyy-MM-dd HH:mm:ss'

// 				},
// 				validationRules: [{
// 					type: "required",
// 					message: "请输入使用日期"
// 				}]

// 			}
// 			]
// 		}]
// 	}
// });

_app.App.registerCrud({
	route: 'today',
	url: $.config('apiUrl') + 'restful?_model=product-attr-group',
	placeholder: '产品',
	title: '产品属性',
	capable: {
		create: true
	},
	search: {
		mobile: 'title'
	},
	columns: [{
		dataField: 'id',
		caption: 'id'
	}, {
		dataField: 'name',
		caption: "名称"
	}, {
		dataField: 'online_at',
		caption: '日期'
	}, {
		dataField: 'id',
		caption: '操作',
		cellTemplate: function cellTemplate(con, opt) {
			$('<a>').text('编辑').click(function () {
				_app.App.getEventContext().redirect('#/today/edit/' + opt.value);
			}).appendTo(con);

			$("<span>|</span>").css('margin', '0 10px').appendTo(con);

			$('<a>').text('删除').click(function () {
				$.crudStore(API("restful?_model=wine_today_potable")).remove(opt.value).then(function (res) {
					new DevExpress.ui.notify("删除成功", "success", 1000);
					_app.App.crudGridInstance().option('dataSource').reload();
				});
			}).appendTo(con);
		}
	}],
	form: {
		readOnly: false,
		showColonAfterLabel: true,
		showValidationSummary: false,
		colCount: 1,
		beforeSubmit: function beforeSubmit(form, id) {
			var formData = form.option('formData');

			form.option('formData', formData);
			return true;
		},
		items: [{
			itemType: "group",
			items: [{
				label: { text: '属性名称' },
				dataField: 'name',
				validationRules: [{
					type: "required",
					message: "请输入内容"
				}]
			}, {
				label: { text: '添加属性' },
				dataField: 'labels',
				editorType: 'ExpertYearScoreList'
			}]

		}]
	}
});


},{"./app":2,"./dx-ext":6,"./page":8,"./util":11}],4:[function(require,module,exports){
'use strict';

var _app = require('./app');

var _util = require('./util');

var _util2 = _interopRequireDefault(_util);

var _page = require('./page');

require('./dx-ext');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var crudGridInstance = $(".data-grid").dxDataGrid("instance");
_app.App.registerRoute({
	name: 'data/order',
	onLoad: function onLoad(context, $container) {

		var origin = context.params.data;

		var orderdata = "",
		    title = void 0,
		    text = void 0,
		    series = void 0,
		    basic = '',
		    columns = void 0;

		if (origin == 'chart-order') {

			orderdata = new DevExpress.data.DataSource({
				store: $.crudStore(API('chart-order'))
			});

			title = '订单数据';

			text = '订单总金额';

			basic = '订单总量';

			series = [{ valueField: "total", name: "订单总量", type: 'bar', axis: 'basic' }, { valueField: "total_fee", name: "订单总金额", axis: 'sale' }];

			columns = [{
				dataField: 'date',
				caption: '日期'
			}, {
				dataField: 'total',
				caption: '全部订单量'
			}, {
				dataField: 'total_fee',
				caption: '订单总金额'
			}, {
				dataField: 'general_quantity',
				caption: '微信订单量'
			}, {
				dataField: 'gift_quantity',
				caption: '积分订单量'
			}, {
				dataField: 'general_fee',
				caption: '微信订单总金额'
			}, {
				dataField: 'gift_fee',
				caption: '积分订单总金额'
			}];
		} else if (origin == "chart-visit") {

			orderdata = new DevExpress.data.DataSource({
				store: $.crudStore(API('chart-visit'))
			});

			title = '浏览数据';

			text = '产品浏览量';

			basic = '二维码来源浏览量';

			series = [{ valueField: "qr_pv", name: "二维码来源浏览量", axis: 'sale' }, { valueField: "pv", name: "普通浏览量", type: 'bar', axis: 'basic' }];

			columns = [{
				dataField: 'date',
				caption: '日期'
			}, {
				dataField: 'total',
				caption: '产品详情页总浏览量'
			}, {
				dataField: 'qr_pv',
				caption: '二维码来源浏览量'
			}, {
				dataField: 'qr_uv',
				caption: '二维码来源浏览人数'
			}, {
				dataField: 'pv',
				caption: '普通来源浏览量'
			}, {
				dataField: 'uv',
				caption: '普通来源浏览人数'
			}];
		} else {

			orderdata = new DevExpress.data.DataSource({
				store: $.crudStore(API('chart-new'))
			});

			title = '新增数据';

			text = '新增用户';

			series = [{ valueField: "count", name: "新增用户", axis: 'sale' }];

			columns = [{
				dataField: 'date',
				caption: '日期'
			}, {
				dataField: 'count',
				caption: '新增用户'
			}, {
				dataField: 'qrcode',
				caption: '二维码来源新增'
			}, {
				dataField: 'other',
				caption: '其他来源新增'
			}];
		}

		var page = new _page.Page($container);

		page.crudLayout({ title: title });

		page.content.html('\n\t\t\t<div class="panel panel-default">\n\t\t\t    <div class="panel-heading font-bold">\n\t\t\t      \u67E5\u770B\u6570\u636E\n\t\t\t    </div>\n\t\t\t    <div class="panel-body">\n\t\t\t    \t<div class="toolbar1"></div>\n\t\t\t    \t<div class="data-chart"></div>\n\t\t\t    \t<div class="toolbar2"></div>\n\t\t\t    \t<div class="data-grid"></div>\n\t\t\t    </div>\n\t\t  \t</div>\n\t\t');

		var filterExpr = { start: '', end: '', type: '' },
		    applyFilterExpr = function applyFilterExpr() {
			var da = _app.App.crudChartInstance().option('dataSource'),
			    ds = $('.data-grid').dxDataGrid('instance').option('dataSource');
			orderdata = new DevExpress.data.DataSource({
				store: $.crudStore(API(origin + '?start=' + filterExpr.start + '&end=' + filterExpr.end + '&type=' + filterExpr.type))
			});
			INSERT();
		};

		var items = [{
			location: 'after',
			widget: 'dxDateBox',
			options: {
				displayFormat: "yyyy-MM-dd",
				dateSerializationFormat: 'yyyy-MM-dd',
				placeholder: '开始时间',
				onValueChanged: function onValueChanged(e) {
					filterExpr.start = e.value;
					applyFilterExpr();
				}
			}
		}, {
			location: 'after',
			widget: 'dxDateBox',
			options: {
				displayFormat: "yyyy-MM-dd",
				dateSerializationFormat: 'yyyy-MM-dd',
				placeholder: '结束时间',
				onValueChanged: function onValueChanged(e) {
					filterExpr.end = e.value;
					applyFilterExpr();
				}
			}
		}];

		if (origin == 'chart-new') {
			items.push({
				location: 'before',
				widget: 'dxSelectBox',
				options: {
					placeholder: '请选择类型',
					dataSource: [{ name: '浏览', type: 'view' }, { name: '订单', type: 'order' }],
					displayExpr: 'name',
					valueExpr: 'type',
					value: 'view',
					onValueChanged: function onValueChanged(e) {
						console.log(e);
						filterExpr.type = e.value;
						applyFilterExpr();
					}
				}
			});
		}

		page.content.find('.toolbar1').dxToolbar({
			items: items
		});

		function INSERT() {
			page.content.find(".data-chart").dxChart({
				palette: "violet",
				dataSource: orderdata,
				rotated: false,
				commonSeriesSettings: {
					argumentField: "date",
					type: 'line',
					bar: {
						barWidth: 20,
						barPadding: 0.5,
						barGroupPadding: 0.5
					}
				},
				margin: {
					bottom: 20
				},
				valueAxis: [{
					// name:'basic',
					// position:'left',
					grid: {
						visible: true
					}
					// title:{
					//     text:basic
					//     }
				}, {
					name: "sale",
					position: "right",
					grid: {
						visible: true
					},
					title: {
						text: text
					}
				}],
				series: series,
				legend: {
					verticalAlignment: "top",
					horizontalAlignment: "right",
					itemTextPosition: "right",
					orientation: 'vertical'
				},
				tooltip: {
					enabled: true,
					customizeTooltip: function customizeTooltip(arg) {
						return {
							html: '<div><div class=\'tooltip-header\'>' + arg.argument + '</div>' + arg.seriesName + ':' + arg.valueText + '</div>'
						};
					}
				}
			});

			page.content.find('.toolbar2').dxToolbar({
				items: [{
					location: 'after',
					widget: 'dxButton',
					options: {
						text: '导出',
						onClick: function onClick(e) {

							window.location = API(origin + '?export=true&start=' + filterExpr.start + '&end=' + filterExpr.end + '&type=' + filterExpr.type);
						}
					}
				}]
			});

			page.content.find('.data-grid').dxDataGrid({
				dataSource: orderdata,
				columns: columns
			});
		}

		INSERT();
	}
});

// App.registerRoute({
// 	name:'manage/gift',
// 	onLoad:function(context,$container){
// 		let page=new Page($container);
// 		let columns =[],title,tooltip,dataSource;
// 		let origin=context.params.data;

//    		if(origin){
//    			columns = [{
// 			caption:'id',
// 			dataField:'id'
// 		},{
// 			caption:'类型',
// 			dataField:'category',
// 			cellTemplate:function($c,d){
// 				let text = '';
// 				switch(d.value){
// 					case 'general':text='普通';break;
// 					case 'product':text='指定商品';break;
// 					case 'importer':text='指定进口商';break;
// 					case 'dealer':text='指定经销商'
// 				};
// 				$c.text(text)

// 			}
// 		},{
// 			caption:'进口商/商品',
// 			dataField:'importerName',
// 			cellTemplate:function($c,d){
// 				let text = d.data.importerName?d.data.importerName:d.data.productName
// 				$c.text(text)
// 			}
// 		},{
// 			caption:'满减类型',
// 			dataField:'couponName'

// 		}]

// 		title = '优惠券管理';

// 		tooltip = '优惠券类型管理列表';

// 		dataSource = $.crudStore(API('restful?_model=sys-coupon-category'))

//    		}else{
//    			columns = [{
//    				caption:"id",
//    				dataField:'id'
//    			},{
//    				caption:'优惠券名称',
//    				dataField:'coupon_name'
//    			},{
//    				caption:'活动名称',
//    				dataField:'name'
//    			},{
//    				caption:'使用量',
//    				dataField:'used'
//    			},{
//    				caption:'领取量',
//    				dataField:'get'
//    			},{
//    				caption:'库存剩余量',
//    				dataField:'sku',
//    				cellTemplate:function(c,d){

//    					let $datagird = page.content.find('.data-grid').dxDataGrid('instance').option('dataSource');

//    					$('<a>').text(d.value).css('text-decoration','underline').click(function(){
//    						let num = prompt('请输入要修改的数值');
//    					if(num) { 
//    					d.data.sku=num
//    					$.crudStore(API('restful?_model=sys-coupon')).update(d.data.id,d.data).then(res=>{
//    						DevExpress.ui.notify({message:'修改成功'},'success',1500)
//    						$datagird.load()
//    					}).fail(function(){
//    						DevExpress.ui.notify({message:'错误'},'warning',1500)
//    					}) }
//    					}).appendTo(c)
//    				}
//    			}];

//    			title = '优惠券使用';

//    			tooltip = '优惠券活动使用列表';

//    			dataSource = $.crudStore(API('restful?_model=sys-coupon'))
//    		}


// 		page.crudLayout({title:title});
// 		page.content.html(`<div class="panel panel-default">
// 			    <div class="panel-heading font-bold">
// 			      ${tooltip}
// 			    </div>
// 			    <div class="panel-body">
// 			    	<div class="toolbar1"></div>
// 			    	<div class="data-grid"></div>
// 			    </div>
// 		  	</div>`);

// 		page.content.find('.toolbar1').dxToolbar({
// 			items:[{
// 				location:'before',
// 				widget:'dxButton',
// 				options:{
// 					text:'增加',
// 					onClick:function(e){
// 						newData()
// 					}
// 				}
// 			}]
// 		});


// 		 page.content.find('.data-grid').dxDataGrid({
// 			dataSource:new DevExpress.data.DataSource({
// 				store:dataSource
// 			}), 
// 			columns:columns
// 		})


// 		function newData(){
// 			let newtitle,new_data,new_items;
// 			var now = new Date();
// 			if(origin){
// 			 newtitle = '新建优惠券';
// 			 new_data = new DevExpress.data.CustomStore({
// 				store:$.crudStore(API('restful?_model=use-coupon'))
// 			});

// 			 new_items = [{
// 				label:{text:'优惠券类型'},
// 				editorType:'dxSelectBox',
// 				dataField:'category',
// 				editorOptions:{
// 					dataSource:[{name:'普通',type:'general'},{name:'指定商品',type:'product'},{name:'指定进口商',type:'importer'}],
// 					displayExpr:'name',
// 					valueExpr:'type',
// 					onValueChanged(e){
// 						let $container = $('.formData').find(".new_tool_data").dxForm('instance');
// 						$container.option('formData.category',e.value);
// 						if(e.value == 'general'){
// 						 	$container.getEditor('importer_id').element().closest('.dx-field-item').addClass('hidden')
// 							$container.getEditor('dealer_id').element().closest('.dx-field-item').addClass('hidden');
// 							$container.option({'formData.importer_id':null,'formData.dealer_id':null});

// 						}else if(e.value == 'product'){
// 							$container.getEditor('importer_id').element().closest('.dx-field-item').removeClass('hidden')
// 							$container.getEditor('dealer_id').element().closest('.dx-field-item').addClass('hidden');
// 							$container.option('formData.dealer_id',null)
// 						}else {
// 							$container.getEditor('dealer_id').element().closest('.dx-field-item').removeClass('hidden')
// 							$container.getEditor('importer_id').element().closest('.dx-field-item').addClass('hidden')
// 							$container.option('formData.importer_id',null)
// 						}

// 					}
// 				}
// 			},
// 			{
// 				dataField:'importer_id',
// 				cssClass:'hidden',
// 				label:{text:'指定商品'},
// 				editorType:'dxSelectBox',
// 				editorOptions:{
// 					dataSource:$.crudStore(API('restful?_model=wine-product')),
// 					valueExpr:'id',
// 					displayExpr:'chname',
// 					placeholder:'指定商品',
// 					onValueChanged:function(ev){
// 					let $container = $('.formData').find(".new_tool_data")
// 					$container.dxForm('instance').option('formData.product_id',ev.value);

// 							}
// 				}
// 			},{
// 				dataField:'dealer_id',
// 				cssClass:'hidden',
// 				label:{text:'指定进口商'},
// 				editorType:'dxSelectBox',
// 				editorOptions:{
// 					dataSource:$.crudStore(API('restful?_model=sys-importer')),
// 					placeholder:'指定进口商',
// 					valueExpr:'id',
// 					displayExpr:'name',
// 					onValueChanged:function(ev){
// 					let $container = $('.formData').find(".new_tool_data")
// 					$container.dxForm('instance').option('formData.importer_id',ev.value);	
// 							}
// 				}
// 			},
// 			{
// 				label:{text:'满减类型'},
// 				editorType:'dxSelectBox',
// 				editorOptions:{
// 					dataSource:[{name:'直减',type:'direct'},{name:'满减',type:'full'}],
// 					valueExpr:'type',
// 					displayExpr:'name',
// 					onValueChanged:function(e){
// 					let $container = $('.formData').find(".new_tool_data").dxForm('instance');	

// 					$container.option('formData.loseType',e.value)

// 					if(e.value == 'direct'){
// 							$container.getEditor('full_amount').element().closest('.dx-field-item').addClass('hidden')
// 						// $container.itemOption('on_select_amount','items',[{label:{text:'直减'},dataField:'amount'}]);
// 					}else{
// 						$container.getEditor('full_amount').element().closest('.dx-field-item').removeClass('hidden')
// 					    // $container.itemOption('on_select_amount',"items",[{label:{text:'满'},dataField:'full_amount'},{label:{text:'减'},dataField:'amount'}])
// 					}


// 					}
// 				}
// 			},{
// 				itemType:'group',
// 				colCount:2,
// 				caption:'on_select_amount',
// 				items:[{
// 					label:{text:'满'},
// 					dataField:'full_amount'
// 				},{
// 					label:{text:'减'},
// 					dataField:'amount'
// 				}]

// 			}]
// 			}else{
// 				newtitle = '新建优惠券活动';
// 				new_data = new DevExpress.data.CustomStore({
// 					store:$.crudStore(API('restful?_model=sys-coupon'))
// 				});

// 				new_items=[{
// 					label:{text:'活动名称'},
// 					dataField:'name'
// 				},{
// 					label:{text:'通用类型'},
// 					dataField:'coupon_category_id',
// 					editorType:'dxSelectBox',
// 					editorOptions:{
// 						dataSource:$.crudStore(API('restful?_model=sys-coupon-category')),
// 						displayExpr:'couponName',
// 						valueExpr:'id',
// 						onValueChanged:function(e){
// 							let $container = $('.formData').find('.new_tool_data').dxForm('instance');
// 							$container.option('formData.coupon_category_id',e.value)
// 						}
// 					}
// 				},{
// 					label:{text:'领取有效期'},
// 					itemType:'group',
// 					colCount:2,
// 					items:[{
// 						dataField:'can_get_start',
// 						label:{text:'自'},
// 						editorType:'dxDateBox',
// 						editorOptions:{
// 							type: "date",
// 							displayFormat: 'yyyy-MM-dd',
// 							dateSerializationFormat: "yyyy-MM-dd",
// 							editorOptions: {
// 							displayFormat: 'yyyy-MM-dd',
// 							dateSerializationFormat: 'yyyy-MM-dd'
// 					}
// 						}
// 					},{
// 						label:{text:'至'},
// 						dataField:'can_get_end',
// 						editorType:'dxDateBox',
// 						editorOptions:{
// 							type: "date",
// 							displayFormat: 'yyyy-MM-dd',
// 							dateSerializationFormat: "yyyy-MM-dd",
// 							editorOptions: {
// 							displayFormat: 'yyyy-MM-dd',
// 							dateSerializationFormat: 'yyyy-MM-dd'
// 					}
// 						}
// 					}]
// 				},{
// 					label:{text:'使用有效期'},
// 					itemType:'group',
// 					colCount:2,
// 					items:[
// 					{	editorType:'dxRadioGroup',
// 						editorOptions:{
// 							layout: "horizontal",
// 							items:[{text:'固定日期',value:'yes'},{text:'浮动日期',value:'no'}],
// 							value:'yes',
// 							valueExpr:'value',
// 							onValueChanged:function(e){
// 								let value = e.value=='yes'?'no':'yes'
// 							let $container = $('.formData').find('.new_tool_data').dxForm('instance');
// 							$container.option('formData.enable_use_date',e.value);
// 							$container.option('formData.enable_use_days',value);
// 							if(e.value ==  'yes'){
// 								$container.getEditor('can_use_start').element().closest(".dx-field-item").removeClass('hidden');
// 								$container.getEditor('can_use_end').element().closest(".dx-field-item").removeClass('hidden');
// 								$container.getEditor('can_use_days').element().closest(".dx-field-item").addClass('hidden');

// 							}else{
// 								$container.getEditor('can_use_start').element().closest(".dx-field-item").addClass('hidden');
// 								$container.getEditor('can_use_end').element().closest(".dx-field-item").addClass('hidden');
// 								$container.getEditor('can_use_days').element().closest(".dx-field-item").removeClass('hidden');

// 							}

// 							}
// 						}
// 					},
// 					{
// 							editorType:'dxTextBox',
// 							cssClass:'hidden'
// 					},
// 					{
// 						dataField:'can_use_start',
// 						label:{text:'自'},
// 						editorType:'dxDateBox',
// 						editorOptions:{
// 							type: "date",
// 							displayFormat: 'yyyy-MM-dd',
// 							dateSerializationFormat: "yyyy-MM-dd",
// 							editorOptions: {
// 							displayFormat: 'yyyy-MM-dd',
// 							dateSerializationFormat: 'yyyy-MM-dd'
// 					}
// 						}
// 					},{
// 						dataField:'can_use_end',
// 						label:{text:'至'},
// 						editorType:'dxDateBox',
// 						editorOptions:{
// 							type: "date",
// 							displayFormat: 'yyyy-MM-dd',
// 							dateSerializationFormat: "yyyy-MM-dd",
// 							editorOptions: {
// 							displayFormat: 'yyyy-MM-dd',
// 							dateSerializationFormat: 'yyyy-MM-dd'
// 					}
// 						}
// 					},{
// 						label:{text:'自领取日期起'},
// 						dataField:'can_use_days',
// 						cssClass:'hidden'
// 					}
// 					]
// 				},{
// 					label:{text:'使用条件'},
// 					editorType:'dxSelectBox',
// 					editorOptions:{
// 						dataSource:[{name:'新用户',value:'new'},{name:'老用户',value:'old'},{name:'新老用户',value:'all'}],
// 						displayExpr:"name",
// 						valueExpr:'value',
// 						onValueChanged:function(e){
// 							let $container = $('.formData').find('.new_tool_data').dxForm('instance');
// 							$container.option('formData.condition',e.value);

// 						}
// 					}
// 				},{
// 					label:{text:'库存量'},
// 					dataField:'sku'
// 				}]

// 			}


// 			$("#popups").html('<div>');

// 			$("<div/>").appendTo($("#popups")).dxPopup({
// 					width:800,
// 					height:600,
// 					visible:true,
// 					title:newtitle,
// 					contentTemplate: function(contentElement) {
// 					return '<div class="formData"><div class="new_tool_data"></div><div class="toolbar2" style="margin:30px auto;display:block"></div></div>'
// 					},
// 					onContentReady:function(e){
// 						let $content = e.component.content();

// 						$content.find('.new_tool_data').dxForm({
// 						dataSource:new_data,
//             			validationGroup: "crud",
//             			items:new_items
// 						});

// 						$content.find('.toolbar2').dxButton({
// 							type:'success',
// 							text:'创建',
// 							onClick:function(){
// 								let data = $('.formData').find('.new_tool_data').dxForm('instance').option('formData');
// 						console.log(data);
// 						let route = ''
// 						if(origin){
// 							route = 'restful?_model=sys-coupon-category'
// 						}else{
// 							route = 'restful?_model=sys-coupon';
// 							data.enable_use_date=data.enable_use_date?data.enable_use_date:'yes';
// 							data.enable_use_days=data.enable_use_days?data.enable_use_days:'no'
// 						};

// 						$.ajax({url:API(route),method:'post',data:data}).always(function(resp){
// 							console.log(resp)
// 							if(resp.status == 'success'){
// 								DevExpress.ui.notify({message:'创建成功'},'success',1500);
// 							$("#popups").find('div').remove();
// 								 page.content.find('.data-grid').dxDataGrid('instance').option('dataSource').reload()
// 							}else{
// 								DevExpress.ui.notify({message:function(){

// 									let text = "提示:"+resp.responseJSON.message;
// 									return text
// 								}},'warning',1500)
// 							}
// 								})

// 							}
// 						})
// 					}
// 				})
// 		}
// 	}
// })

_app.App.registerRoute({
	name: 'modify_pwd',
	onLoad: function onLoad(content, $container) {
		var page = new _page.Page($container);
		page.content.html('<div class="panel panel-default">\n\t\t    <div class="panel-heading font-bold">\n\t\t\t     \u4FEE\u6539\u5BC6\u7801\n\t\t\t    </div>\n\t\t\t    <div class="crud-container crud-reset row">\n\t\t\t      \t<div class="col-md-12">\n\t\t\t    \t\t<div class="data-grid" style=\'padding:50px;border:0\'></div>\n\t\t\t    \t</div>\n\t\t\t      \t<div class="col-md-12">\n\t\t\t     \t\t<div class="toolbar2" style=\'padding:0 130px\'></div>\n\t\t\t      \t</div>\n\t\t\t    </div>\n\n\t\t  \t</div>');

		page.content.find('.data-grid').dxForm({
			readOnly: false,
			showColonAfterLabel: true,
			showValidationSummary: false,
			colCount: 1,
			items: [{
				dataField: 'old_password',
				label: { text: '原密码' },
				editorOptions: {
					mode: 'password'
				},
				validationRules: [{
					type: "required"
				}]
			}, {
				dataField: 'password',
				label: { text: '新密码' },
				editorOptions: {
					mode: 'password'
				},
				validationRules: [{
					type: "required"
				}]
			}, {
				dataField: 'password_confirmation',
				label: { text: "确认密码" },
				editorOptions: {
					mode: 'password'
				},
				validationRules: [{
					type: "required"
				}]
			}]
		});

		page.content.find('.toolbar2').dxToolbar({
			items: [{
				location: 'before',
				widget: "dxButton",
				options: {
					text: '确认修改',
					type: 'success',
					onClick: function onClick() {
						var data = page.content.find('.data-grid').dxForm('instance').option('formData');
						$.ajax({
							url: API('auth/change-password'),
							headers: { Authorization: "bearer " + localStorage.accessToken },
							method: 'post',
							data: data,
							success: function success(res) {

								DevExpress.ui.notify({ message: '修改成功' }, 'success', 1500);
								setTimeout(function () {
									window.location.href = 'login.html';
								}, 1500);
							},
							error: function error(err) {
								DevExpress.ui.notify({ message: function message() {
										var text = '提示 ：' + err.responseJSON.message;
										return text;
									} }, 'warning', 2000);
							}
						});
					}
				}
			}]
		});
	}

});


},{"./app":2,"./dx-ext":6,"./page":8,"./util":11}],5:[function(require,module,exports){
'use strict';

var _app = require('./app');

var _util = require('./util');

var _util2 = _interopRequireDefault(_util);

var _page = require('./page');

require('./dx-ext');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

_app.App.registerRoute({
	name: "price",
	onLoad: function onLoad(context, $container) {
		var page = new _page.Page($container);
		var ID = context.params.id;
		var _reload = '';
		page.crudLayout({ title: "价格列表" });
		page.content.html('<div class="panel panel-default">\n\t\t    <div class="panel-heading font-bold">\n\t\t\t      \u5546\u54C1\u4EF7\u683C\u8BE6\u60C5\n\t\t\t    </div>\n\t\t\t    <div class="panel-body">\n\t\t\t    \t<div class="toolbar1"></div>\n\t\t\t    \t<div class="data-grid"></div>\n\t\t\t    </div>\n\t\t  \t</div>');

		var new_list = function newData() {
			var sku_id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

			var newtitle = '新建';
			if (sku_id) {
				newtitle = '修改';
			}
			$("#popups").html('<div>');

			$("<div/>").appendTo($("#popups")).dxPopup({
				width: 800,
				height: 600,
				visible: true,
				title: newtitle,
				contentTemplate: function contentTemplate(contentElement) {
					return '<div class="formData"><div class="new_tool_data"></div><div class="toolbar2" style="margin:30px auto;display:block"></div></div>';
				},
				onContentReady: function onContentReady(e) {
					var $content = e.component.content();
					var sku_attr = [];
					var origin_price = [{
						label: { text: '市场价' },
						dataField: "origin_price",
						validationRules: [{
							type: "required",
							message: '请输入市场价'
						}]
						// 					,{
						// 						label:{text:'促销价'},
						// 						dataField:"price",
						// 					
						// 						validationRules: [{
						//                     type: "required",
						//                     message:'请输入促销价'
						//                   		}]
						// 					},{
						// 						label:{text:'二档优惠价'},
						// 						dataField:"price_3_4",
						// 					
						// 						validationRules: [{
						//                     type: "required",
						//                     message:'请输入二档优惠价'
						//                   		}]
						// 					},{
						// 						label:{text:'三档优惠价'},
						// 						dataField:"price_5",
						// 					
						// 						validationRules: [{
						//                     type: "required",
						//                     message:'请输入三档优惠价'
						//                   		}]
						// 					}
					}, {
						label: { text: '库存' },
						dataField: "sku",

						validationRules: [{
							type: "required",
							message: '请输入库存'
						}]
					}];

					$.get($.config('apiUrl') + ('product/' + ID + '/labels')).then(function (res) {
						var select_list = res.data.labels;
						var items = {
							colCount: 2,
							itemType: 'group',
							items: []
						};
						function attene() {
							var resp = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

							$.each(select_list, function (i, item) {
								var _list;

								var attr = {
									attr_label_id: item.id,
									attr_value_id: ''
								};
								sku_attr.push(attr);
								var editor = {
									dataSource: item.values,
									displayExpr: 'value',
									valueExpr: "id",
									onValueChanged: function onValueChanged(e) {
										console.log(e);
										sku_attr[i].attr_value_id = e.value;
									}
								};

								if (resp) {
									resp.forEach(function (is) {
										if (is.attr_label_id == item.id) {
											editor['value'] = is.attr_value_id;
											sku_attr[i].attr_value_id = is.attr_value_id;
										}
									});
								}

								var list = (_list = {
									label: { text: item.name },
									editorType: 'dxSelectBox',
									validationRules: [{
										type: "required",
										message: '请选择' + item.name
									}]
								}, _defineProperty(_list, 'editorType', 'dxSelectBox'), _defineProperty(_list, 'editorOptions', editor), _list);
								items['items'].push(list);
							});
						}

						if (sku_id) {
							$.get($.config('apiUrl') + ('restful/' + sku_id + '?_model=product-sku')).then(function (resp) {
								var sku_data = resp.data;
								attene(sku_data.sku_attr);
								items['items'] = items['items'].concat(origin_price);

								$content.find('.new_tool_data').dxForm({
									formData: sku_data,
									showColonAfterLabel: true,
									showValidationSummary: false,
									validationGroup: "crud",
									alignItemLabels: true,
									alignItemLabelsInAllGroups: true,
									items: [items]
								});
							});
						} else {
							attene();
							items['items'] = items['items'].concat(origin_price);

							$content.find('.new_tool_data').dxForm({
								// formData:sku,
								showColonAfterLabel: true,
								showValidationSummary: false,
								validationGroup: "crud",
								alignItemLabels: true,
								alignItemLabelsInAllGroups: true,
								items: [items]
							});
						}
					});

					$content.find('.toolbar2').dxButton({
						type: 'success',
						text: newtitle,
						onClick: function onClick() {
							var data = $('.formData').find('.new_tool_data').dxForm('instance').option('formData');
							console.log(data);
							data['sku_attr'] = sku_attr;
							data['product_id'] = ID;
							if (sku_id) {
								$.ajax({
									url: $.config('apiUrl') + ('restful/' + sku_id + '?_model=product-sku'),
									data: data,
									type: 'PUT',
									success: function success(dat) {
										if (dat.code == '200' && dat.status == 'success') {
											DevExpress.ui.notify(newtitle + '成功', 'success', 1500);
											$("#popups").find('div').remove();
											_reload();
										} else {
											var message = dat.message ? dat.message : '保存失败';
											DevExpress.ui.notify(message, 'warning', 1500);
										}
									},
									error: function error(dt, te, er) {
										console.error(dt, te, er);
										DevExpress.ui.notify(newtitle + '失败', 'warning', 1500);
									}
								});
							} else {

								$.post($.config('apiUrl') + 'restful?_model=product-sku', data, function (dat, textstatus, datatype) {
									console.log(data);
									if (dat.code == '200' && dat.status == 'success') {
										DevExpress.ui.notify(newtitle + '成功', 'success', 1500);
										$("#popups").find('div').remove();
										_reload();
									}
								});
							}
						}
					});
				}
			});
		};

		var param = '{"filter":["product_id","=",' + ID + ']}';
		_reload = function reload() {
			$.get($.config('apiUrl') + 'restful?_model=product-sku&_param=' + param).then(function (res) {
				var data = res.data;

				var set_price = function set_price(id, key) {
					var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';

					var num = prompt('请输入', value ? value : '0');
					if (num) {
						$.post($.config('apiUrl') + "state-change", {
							'changeType': 'productSku',
							'changeKey': key,
							'changeValue': num,
							'changeId': id
						}, function (res) {
							if (res.status) {
								DevExpress.ui.notify({
									message: function message() {
										_reload();
										return '修改成功';
									}
								}, "success", 1000);
							} else {
								DevExpress.ui.notify({
									message: function message() {
										return '操作失败';
									}
								}, "warning", 1000);
							}
						});
					}
				};

				var price = [{
					dataField: 'skuCode',
					caption: "编号"
				}, {
					dataField: 'desc',
					caption: '样式'
				}, {
					dataField: 'origin_price',
					caption: "市场价",
					cellTemplate: function cellTemplate($c, d) {
						var sid = d.key.id;
						$("<div>").text(d.value).css({ 'text-decoration': 'underline', 'cursor': 'pointer' }).click(function () {
							set_price(sid, 'origin_price', d.value);
						}).appendTo($c);
					}

				}, {
					dataField: 'price',
					caption: '优惠价'
					// 				cellTemplate:function($c,d){
					// 					let sid = d.key.id
					// 					$("<div>").text(d.value).css({'text-decoration':'underline','cursor':'pointer'}).click(function(){
					// 						set_price(sid,'price',d.value)
					// 					}).appendTo($c)
					// 				}

					// 			,{
					// 				dataField:'price_3_4',
					// 				caption:'二档优惠价',
					// 				cellTemplate:function($c,d){
					// 					let sid = d.key.id
					// 					$("<div>").text(d.value).css({'text-decoration':'underline','cursor':'pointer'}).click(function(){
					// 						set_price(sid,'price_3_4',d.value)
					// 					}).appendTo($c)
					// 				}
					// 				
					// 			},{
					// 				dataField:'price_5',
					// 				caption:'三档优惠价',
					// 				cellTemplate:function($c,d){
					// 					let sid = d.key.id
					// 					$("<div>").text(d.value).css({'text-decoration':'underline','cursor':'pointer'}).click(function(){
					// 						set_price(sid,'price_5',d.value)
					// 					}).appendTo($c)
					// 				}
					// 				
					// 			},
				}, {
					dataField: "consume_price",
					caption: '积分价'
				}, {
					dataField: 'sku',
					caption: "库存",
					cellTemplate: function cellTemplate($c, d) {
						var sid = d.key.id;
						$("<div>").text(d.value).css({ 'text-decoration': 'underline', 'cursor': 'pointer' }).click(function () {
							set_price(sid, 'sku', d.value);
						}).appendTo($c);
					}
				}, {
					dataField: "id",
					caption: '操作',
					cellTemplate: function cellTemplate($c, d) {
						console.log(d);
						$('<div>').text('删除').css({ 'text-decoration': 'underline', 'cursor': 'pointer' }).click(function () {
							$.ajax({
								url: $.config('apiUrl') + ('restful/' + d.value + '?_model=product-sku'),
								type: 'delete',
								success: function success(data) {
									console.log(data);
									if (data.status == 'success') {
										DevExpress.ui.notify('删除成功', 'success', 1500);
										$("#popups").find('div').remove();
										_reload();
									} else {
										var message = dat.message ? dat.message : '保存失败';
										DevExpress.ui.notify(message, 'warning', 1500);
									}
								},
								error: function error(er, dx, ht) {
									DevExpress.ui.notify('未知错误', 'warning', 1500);
									console.error(er, dx, ht);
								}
							});
						}).appendTo($c);
					}
					// cellTemplate:function($c,d){
					// 	console.log(d)
					// 	$('<div>').text('修改').click(function(){
					// 		new_list(d.value)
					// 	}).appendTo($c)
					// }
				}];

				page.content.find('.data-grid').dxDataGrid({
					dataSource: data,
					columns: price
				});

				page.content.find('.toolbar1').dxToolbar({
					items: [{
						location: 'before',
						widget: 'dxButton',
						options: {
							text: '增加',
							onClick: function onClick(e) {
								new_list();
							}
						}
					}]
				});
			});
		};

		_reload();
	}
});

// App.registerRoute({
// 	name:"data/dealer",
// 	onLoad:function(context,$container){
// 		let page=new Page($container);

// 		let origin=context.params.id;
// 		let origin_name = context.params.name;
// 		let columns="";
// 		if(origin){
// 			page.crudLayout({title:"经销商管理"});
// 			page.content.html(`<div class="panel panel-default">
// 		    <div class="panel-heading font-bold">
// 			      进口商${origin_name}
// 			    </div>
// 			    <div class="panel-body">
// 			    	<div class="toolbar1"></div>
// 			    	<div class="data-grid"></div>
// 			    </div>
// 		  	</div>`);	
// 			let filter = [['importer_id','=',origin]]

// 			let store = $.crudStore(API('restful?_model=sys-importer-dealer'), {
// 					onLoading: function(loadOptions) {
// 						loadOptions.filter = filter;
// 					}
// 				});
// 			columns = {
// 				dataSource:store,
// 				columns:[{
// 					caption:'id',
// 					dataField:'id'
// 				},{
// 					caption:'经销商名称',
// 					dataField:'dealer.name'
// 				},{
// 					caption:'备注',
// 					dataField:'remark'
// 				},{
// 					caption:'地址',
// 					dataField:'dealer.area_name'
// 				},{
// 					caption:'操作',
// 					dataField:'dealer.id',
// 					cellTemplate:function(container,options){
// 						$("<a>").text('编辑').css({"text-decoration":"underline"}).click(function(){
// 							App.getEventContext().redirect(`#/data/new_dealer?openid=${options.data.dealer.id}&id=${origin}&name=${origin_name}`)
// 						}).appendTo(container)
// 					}
// 				}]
// 			}

// 			page.content.find('.toolbar1').dxToolbar({
// 			items:[{
// 				widget:'dxButton',
// 			location:"before",
// 			options:{
// 				text:"增加经销商",
// 				onClick:function(e){
// 						App.getEventContext().redirect(`#/data/new_dealer?id=${origin}&name=${origin_name}&dataset=${origin}`); 
// 					}
// 				}
// 			}]
// 		});

// 		}else{ 

// 		page.crudLayout({title:'进口商管理'});
// 		page.content.html(`<div class="panel panel-default">
// 		    <div class="panel-heading font-bold">
// 			      进口商管理
// 			    </div>
// 			    <div class="panel-body">
// 			    	<div class="toolbar1"></div>
// 			    	<div class="data-grid"></div>
// 			    </div>
// 		  	</div>`);

// 		columns = {
// 			dataSource:$.crudStore(API("restful?_model=sys-importer")),
// 			columns:[{
// 				caption:'id',
// 				dataField:'id'
// 			},{
// 				caption:'进口商名称',
// 				dataField:'name'
// 			},{
// 				caption:'备注',
// 				dataField:'remark'
// 			},{
// 				caption:'经销商',
// 				dataField:'dealers_name'
// 			},{
// 				caption:'操作',
// 				dataField:"id",
// 				cellTemplate:function(container,options){
// 					let $html = $('<div><a>编辑</a> |<a>添加经销商</a></div>')
// 					$html.find("a").css({"text-decoration":'underline'})

// 					$html.find('a:first').click(function(){
// 						App.getEventContext().redirect(`#/data/new_dealer?importer=${options.value}`);
// 					})

// 					$html.find('a:last').click(function(){
// 						App.getEventContext().redirect(`#/data/dealer?id=${options.value}&name=${options.data.name}`);
// 					})

// 					$html.appendTo(container)

// 				}
// 			}]
// 		}

// 			page.content.find('.toolbar1').dxToolbar({
// 			items:[{
// 				widget:'dxButton',
// 			location:"before",
// 			options:{
// 				text:"增加",
// 				onClick:function(e){
// 						App.getEventContext().redirect('#/data/new_dealer'); 
// 					}
// 				}
// 			}]
// 		});

// 			}


// 	 page.content.find('.data-grid').dxDataGrid(columns)

// 	}
// })


// App.registerRoute({
// 	name:'data/new_dealer',
// 	onLoad:function(context,$container){
// 		let page=new Page($container);
// 		let origin=context.params.dataset;
// 		let origin_id=context.params.openid;
// 		let origin_name = context.params.name;
// 		let ID = context.params.id;
// 		let importer = context.params.importer;

// 		console.log(importer);

// 		if(origin || origin_id || ID){
// 			page.crudLayout({title:'经销商'});

// 			page.content.html(`<div class="panel panel-default">
// 			    <div class="panel-heading font-bold">
// 			      经销商管理
// 			    </div>
// 			    <div class="panel-body">
// 			    	<div class="data-grid"></div>
// 			    </div>
// 		  	</div>`);

// 			page.content.find(".data-grid").css({"padding":"20px"});

// 			let store = '';


// 			let items = [{
// 				colCount:2,
// 				itemType:'group',
// 				items:[{
// 					label:{text:'经销商名称'},
// 					dataField:'name'
// 				},{
// 					label:{text:' '},
// 					editorType:'dxSelectBox',
// 					editorOptions:{
// 						dataSource:$.crudStore(API("restful?_model=sys-dealer")),
// 						displayExpr:'name',
// 						valueExpr:'id',
// 						showClearButton:true,
// 						searchEnabled:true,
// 						onValueChanged:function(e){

// 							let instance = page.content.find(".data-grid").dxForm('instance')
// 							$.get(API(`restful/${e.value}?_model=sys-dealer`)).then(res =>{
// 								instance.option('formData',res.data);
// 								let area_code=res.data.area_code;
// 								if(area_code){ 
// 								let country = area_code.slice(0,2)+'0000',city=area_code.slice(0,4)+'00' 
// 								$.get(API("areas")).then(resp =>{
// 										let data =  resp;

// 									page.content.find(".select_country").dxSelectBox("instance").option("dataSource",resp);
// 									page.content.find(".select_country").dxSelectBox("instance").option("value",country);
// 									data.forEach( item =>{
// 										if(item.value == country){

// 											page.content.find(".select_city").dxSelectBox("instance").option("dataSource",item.child);
// 											page.content.find(".select_city").dxSelectBox("instance").option("value",city);
// 											return item.child.forEach(it=>{
// 												if(it .value == city)
// 												page.content.find(".select_region").dxSelectBox("instance").option("dataSource",it.child);
// 												page.content.find(".select_region").dxSelectBox("instance").option("value",area_code);

// 													})
// 												}
// 											})

// 								})
// 								};
// 							})

// 						}
// 					}

// 				}]
// 			},{
// 				label:{text:'地址'},
// 				itemType:'group',
// 				colCount:3,
// 				items:[{
// 					label:{text:'省级'},
// 					template:function(data){
// 					return $("<div class='select_country'>").dxSelectBox({
// 								placeholder:'请选择省级',
// 								dataSource:$.crudStore(API("areas")),
// 								displayExpr:"name",
// 								valueExpr:'value',
// 								searchEnabled:true,
// 								onSelectionChanged:function(e){

// 									if(!e.selectedItem){return }
// 							page.content.find(".select_city").dxSelectBox("instance").option('dataSource',e.selectedItem.child);
// 							page.content.find(".select_region").dxSelectBox("instance").option("dataSource",[])
// 								}
// 							})
// 					}
// 				},{
// 					label:{text:'市级'},
// 					template:function(data){
// 					return	$("<div class='select_city'>").dxSelectBox({placeholder:'请选择市级',displayExpr:"name",
// 								valueExpr:'value',
// 								searchEnabled:true,
// 								noDataText:'请先选择前一级',
// 								onSelectionChanged:function(e){
// 									if(!e.selectedItem){return }
// 									page.content.find(".select_region").dxSelectBox("instance").option("dataSource",e.selectedItem.child)
// 								}
// 							})
// 					}
// 				},{
// 					label:{text:'地区'},
// 					template:function(data){
// 					return	$("<div class='select_region'>").dxSelectBox({placeholder:'请选择区域',displayExpr:"name",
// 								valueExpr:'value',
// 								searchEnabled:true,
// 								noDataText:'请先选择前一级',
// 								onSelectionChanged:function(e){

// 									if(!e.selectedItem){return }
// 									page.content.find(".data-grid").dxForm("instance").option('formData.area_code',e.selectedItem.value);
// 								}
// 							})
// 					}
// 				}]
// 			},{
// 				label:{text:'具体门牌号'},
// 				dataField:'detail'
// 			},{
// 				label:{text:'联系电话'},
// 				dataField:'tel'
// 			},
// 			{
// 				editorType:'dxButton',
// 				editorOptions:{
// 					text:function(){if(origin_id){return '修改'}else{return '创建'}},
// 					type:'success',
// 					useSubmitBehavior:false,
// 					onClick:function(e){
// 						let data=page.content.find(".data-grid").dxForm("instance").option('formData');
// 						data.importer_id=origin;
// 						if(origin_id){
// 							$.crudStore(API(`restful?_model=sys-dealer`)).update(origin_id,data).then((index,res)=>{

// 							DevExpress.ui.notify({message:"修改成功"},"success",1500) ;

// 							setTimeout(function(){window.history.go(-1)},1500)

// 						}).fail(res=>{
// 							DevExpress.ui.notify({message:"请检查"},"warning",2000) 
// 						})

// 						return
// 						}
// 						$.ajax({url:API('restful?_model=sys-dealer'),method:'post',data:data}).always((res)=>{
// 							if(res.status == 'success'){ 
// 							DevExpress.ui.notify({message:"创建成功"},"success",1500) ;

// 							setTimeout(function(){window.history.go(-1);},1500)

// 						}else{  
// 								DevExpress.ui.notify({message:function(){
// 									let text = '错误：'+res.responseJSON.message;
// 									return text
// 								}},"warning",1500) 
// 							}
// 						})
// 					}
// 				}
// 			}
// 			];

// 			if(origin_id){
// 				store = $.crudStore(API(`restful/${origin_id}?_model=sys-dealer`));
// 				$.get(API(`restful/${origin_id}?_model=sys-dealer`)).then(res =>{
// 					page.content.find(".data-grid").dxForm({
// 					formData:res.data,
// 					showColonAfterLabel: true,
// 					colCount:1,
// 					items:items
// 					})


// 				let area_code=res.data.area_code;

// 				let country = area_code.slice(0,2)+'0000',city=area_code.slice(0,4)+'00' ;
// 								$.get(API("areas")).then(resp =>{
// 									let data =  resp;
// 									page.content.find(".select_country").dxSelectBox("instance").option("dataSource",resp);
// 									page.content.find(".select_country").dxSelectBox("instance").option("value",country);
// 									data.forEach( item =>{
// 										if(item.value == country){

// 											page.content.find(".select_city").dxSelectBox("instance").option("dataSource",item.child);
// 											page.content.find(".select_city").dxSelectBox("instance").option("value",city);
// 											return item.child.forEach(it=>{
// 												if(it .value == city)
// 												page.content.find(".select_region").dxSelectBox("instance").option("dataSource",it.child);
// 												page.content.find(".select_region").dxSelectBox("instance").option("value",area_code);

// 													})
// 												}
// 											})
// 									})
// 								})


// 			}else{
// 				page.content.find(".data-grid").dxForm({
// 				dataSource:new DevExpress.data.CustomStore({
//             	store:$.crudStore(API('restful?_model=sys-dealer'))
//         			  }),
// 				showColonAfterLabel: true,
// 				colCount:1,
// 				items:items
// 					})
// 			}


// 			return 
// 		}


// 		let items = [{
// 				label:{text:'进口商名称'},
// 				dataField:'name'
// 			},{
// 				label:{text:'地址'},
// 				itemType:'group',
// 				colCount:3,
// 				items:[{
// 					label:{text:'省级'},
// 					template:function(data){
// 					return $("<div class='select_country'>").dxSelectBox({
// 								placeholder:'请选择省级',
// 								dataSource:$.crudStore(API("areas")),
// 								displayExpr:"name",
// 								valueExpr:'value',
// 								searchEnabled:true,
// 								onSelectionChanged:function(e){

// 									if(!e.selectedItem){return }
// 							page.content.find(".select_city").dxSelectBox("instance").option('dataSource',e.selectedItem.child);
// 							page.content.find(".select_region").dxSelectBox("instance").option("dataSource",[])
// 								}
// 							})
// 					}
// 				},{
// 					label:{text:'市级'},
// 					template:function(data){
// 					return	$("<div class='select_city'>").dxSelectBox({placeholder:'请选择市级',displayExpr:"name",
// 								valueExpr:'value',
// 								searchEnabled:true,
// 								noDataText:'请先选择前一级',
// 								onSelectionChanged:function(e){
// 									if(!e.selectedItem){return }
// 									page.content.find(".select_region").dxSelectBox("instance").option("dataSource",e.selectedItem.child)
// 								}
// 							})
// 					}
// 				},{
// 					label:{text:'地区'},
// 					template:function(data){
// 					return	$("<div class='select_region'>").dxSelectBox({placeholder:'请选择区域',displayExpr:"name",
// 								valueExpr:'value',
// 								searchEnabled:true,
// 								noDataText:'请先选择前一级',
// 								onValueChanged:function(e){
// 									page.content.find(".data-grid").dxForm("instance").option('formData.area_code',e.value);
// 								}
// 							})
// 					}
// 				}]
// 			},{
// 				label:{text:'具体门牌号'},
// 				dataField:'detail'
// 			},{
// 				label:{text:'联系人'},
// 				dataField:'linkman'
// 			},{
// 				label:{text:"电话"},
// 				dataField:'tel'
// 			},{
// 				label:{text:"邮箱"},
// 				dataField:'email'
// 			},{
// 				editorType:'dxButton',
// 				editorOptions:{
// 					text:function(){
// 						if(importer){
// 							return '修改'
// 						}else{
// 							return '创建'
// 						}},
// 					type:'success',
// 					useSubmitBehavior:false,
// 					onClick:function(e){

// 						let data=page.content.find(".data-grid").dxForm("instance").option('formData');
// 						let URL = 'restful?_model=sys-importer';
// 						let method = 'post';
// 						let text = '创建';
// 						if(importer){ 
// 							URL = `restful/${importer}?_model=sys-importer`;
// 							method = 'PUT';
// 							text = '修改'
// 						}

// 						$.ajax({url:API(URL),method:method,data:data}).always((res)=>{
// 							if(res.status == 'success'){ 
// 							DevExpress.ui.notify({message:text+"成功"},"success",1500) ;


// 							setTimeout(function(){window.history.go(-1);},1500)

// 						}else{
// 								DevExpress.ui.notify({message:function(){
// 									let text = '错误：'+res.responseJSON.message;
// 									return text
// 								}},"warning",1500)
// 							}
// 						}).fail(res=>{
// 							DevExpress.ui.notify({message:"请检查"},"warning",2000) 
// 						})
// 					}
// 				}
// 			}]


// 		if(importer){
// 			page.crudLayout({title:'编辑进口商'});

// 			page.content.html(`<div class="panel panel-default">
// 			    <div class="panel-heading font-bold">
// 			      进口商管理
// 			    </div>
// 			    <div class="panel-body">
// 			    	<div class="data-grid"></div>
// 			    </div>
// 		  	</div>`);

// 		page.content.find(".data-grid").css({"padding":"20px"});


// 			$.get(API(`restful/${importer}?_model=sys-importer`)).then(res => {

// 			page.content.find(".data-grid").dxForm({
// 			formData:res.data,
// 			showColonAfterLabel: true,
// 			colCount:1,
// 			items:items
// 		})
// 			let area_code=res.data.area_code;

// 				let country = area_code.slice(0,2)+'0000',city=area_code.slice(0,4)+'00' ;
// 								$.get(API("areas")).then(resp =>{
// 									let data =  resp;
// 									page.content.find(".select_country").dxSelectBox("instance").option("dataSource",resp);
// 									page.content.find(".select_country").dxSelectBox("instance").option("value",country);
// 									data.forEach( item =>{
// 										if(item.value == country){
// 											page.content.find(".select_city").dxSelectBox("instance").option("dataSource",item.child);
// 											page.content.find(".select_city").dxSelectBox("instance").option("value",city);
// 											return item.child.forEach(it=>{
// 												if(it .value == city)
// 												page.content.find(".select_region").dxSelectBox("instance").option("dataSource",it.child);
// 												page.content.find(".select_region").dxSelectBox("instance").option("value",area_code);

// 													})
// 												}
// 											})
// 									})

// 			})

// 		}else{
// 			page.crudLayout({title:'新建进口商'});

// 			page.content.html(`<div class="panel panel-default">
// 			    <div class="panel-heading font-bold">
// 			      进口商管理
// 			    </div>
// 			    <div class="panel-body">
// 			    	<div class="data-grid"></div>
// 			    </div>
// 		  	</div>`);

// 		page.content.find(".data-grid").css({"padding":"20px"});

// 			page.content.find(".data-grid").dxForm({
// 			dataSource:new DevExpress.data.CustomStore({
//             store: $.crudStore(API('restful?_model=sys-importer'))
//           }),
// 			showColonAfterLabel: true,
// 			colCount:1,
// 			items:items
// 		})
// 		}


// 	}
// })


},{"./app":2,"./dx-ext":6,"./page":8,"./util":11}],6:[function(require,module,exports){
"use strict";

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

jQuery.fn.extend({

	crudForm: function crudForm(options) {
		if ((typeof options === "undefined" ? "undefined" : _typeof(options)) === 'object') {}
	},

	dxInit: function dxInit() {
		$("[dx-toggle]", $(this)).each(function () {
			if ($(this).hasClass("dx-widget")) {
				return true;
			}

			var type = $(this).attr("dx-toggle"),
			    options = $(this).attr("dx-options") || "{}";

			try {
				options = JSON.parse(options);
			} catch (ex) {

				options = {};
			}

			switch (type) {
				case "button":
					$(this).dxButton(options);
					break;

				case "select":
					$(this).dxSelectBox(options);
					break;

				case "text":
					$(this).dxTextBox(options);
					break;

				case "textarea":
					$(this).dxTextArea(options);
					break;

				case "number":
					$(this).dxNumberBox(options);
					break;

				case "check":
					$(this).dxCheckBox($.extend({
						text: $(this).text()
					}, options));
					break;

				default:
					console.log("Error: unsupported type " + type);
					break;
			}
		});

		return $(this);
	},
	dxDelete: function dxDelete(url, option) {
		$("<a>").text("删除").click(function () {
			var id = option.key.id;
			DevExpress.ui.dialog.confirm("确定删除吗?", "请确认").done(function (sele) {

				if (sele) {

					$.ajax({
						type: "delete",
						url: $.config('apiUrl') + "restful/" + id + "?_model=" + url
					}).then(function (a) {

						if (a.status = "success") {

							DevExpress.ui.notify({
								message: function message() {

									var gridComponent = $("#content .crud-grid").dxDataGrid('instance');

									gridComponent.option('dataSource').load();

									return "成功删除";
								}
							}, "success", 1000);
						} else {

							DevExpress.ui.notify({

								message: function message() {

									return "操作失败";
								}
							}, "warning", 1000);
						}
					});
				}
			});
		}).appendTo(this);
		return this;
	},
	dxUpdown: function dxUpdown(url, option) {
		var text = option.value == 'yes' ? '下线' : '上线',
		    off = option.value == 'yes' ? 'no' : 'yes';

		$('<a>').text(text).css({
			'text-decoration': 'underline'
		}).click(function () {
			$.post($.config('apiUrl') + "state-change", {
				'changeType': url,
				'changeKey': 'online',
				'changeValue': off,
				'changeId': option.key.id
			}, function (d) {
				if (d.status) {
					DevExpress.ui.notify({
						message: function message() {
							var gridComponent = $("#content .crud-grid").dxDataGrid('instance');
							gridComponent.option('dataSource').load();
							return off == 'yes' ? '上线成功' : '下线成功';
						}
					}, "success", 1000);
				} else {
					DevExpress.ui.notify({
						message: function message() {
							return '操作失败';
						}
					}, "warning", 1000);
				}
			});
		}).appendTo(this);
		return this;
	},
	dxWeight: function dxWeight(url, option) {

		$('<a>').text(option.value == null ? '无' : option.value).css({
			'text-decoration': 'underline'
		}).click(function () {
			var number = prompt('请输入权重', option.value);
			if (number == null) {
				return;
			};
			if (number >= 0 && number <= 100) {
				$.post($.config('apiUrl') + "state-change", {
					'changeType': url,
					'changeKey': 'weight',
					'changeValue': number,
					'changeId': option.key.id
				}, function (d) {
					if (d.status) {
						DevExpress.ui.notify({
							message: function message() {
								var gridComponent = $("#content .crud-grid").dxDataGrid('instance');
								gridComponent.option('dataSource').load();
								return '修改成功';
							}
						}, "success", 1000);
					} else {
						DevExpress.ui.notify({
							message: function message() {
								return '操作失败';
							}
						}, "warning", 1000);
					}
				});
			} else {
				DevExpress.ui.notify({
					message: '请输入正确的值'
				}, 'warning', 1000);
			}
		}).appendTo(this);
		return this;
	},
	dxsetsku: function dxsetsku(url, option) {
		$("<a>").text(option.value ? option.value : '0').css({
			'text-decoration': 'underline'
		}).click(function () {
			var num = prompt('请输入库存', option.value ? option.value : '0');
			if (num >= 0) {
				$.post($.config('apiUrl') + "state-change", {
					'changeType': url,
					'changeKey': 'sku',
					'changeValue': num,
					'changeId': option.key.id
				}, function (res) {
					if (res.status) {
						DevExpress.ui.notify({
							message: function message() {
								var gridComponent = $("#content .crud-grid").dxDataGrid('instance');
								gridComponent.option('dataSource').load();
								return '修改成功';
							}
						}, "success", 1000);
					} else {
						DevExpress.ui.notify({
							message: function message() {
								return '操作失败';
							}
						}, "warning", 1000);
					}
				});
			} else {
				DevExpress.ui.notify({
					message: '请输入正确的值'
				}, 'warning', 1000);
			}
		}).appendTo(this);
		return this;
	}
});

var DxExtInstance = klass(function ($container, config, opt) {
	this.$container = $container;
	this.opt = $.extend({}, opt);
	this.config = $.extend({}, config);
	this.user = {};

	this.config.init.call(this, this.$container, opt);

	this.setValue(opt.value || undefined);
}).statics({
	validate: function validate(formInstance) {
		var editors = [];

		function _check(o) {
			if (o.dataField) {
				var editor = formInstance.getEditor(o.dataField);
				if (editor && typeof editor.isExtInstance === 'function') {
					editors.push(editor);
				}
			} else if (o.items) {
				$.each(o.items, function (i, item) {
					_check(item);
				});
			}
		}

		_check({
			items: formInstance.option('items')
		});

		var result = true;
		$.each(editors, function (i, e) {
			if (!e.validate()) result = false;
		});

		return result;
	},

	define: function define(config) {
		var obj = {};
		obj[config.name] = function () {
			var instance = $(this).data('dx-ext-instance');

			if (arguments.length > 0 && _typeof(arguments[0]) === 'object') {

				if (!instance) {
					instance = new DxExtInstance($(this), config, arguments[0]);
					$(this).data('dx-ext-instance', instance);
				}

				return $(this);
			} else if (arguments.length > 0 && typeof arguments[0] === 'string') {
				var args = [];
				for (var i = 1; i < arguments.length; i++) {
					args.push(arguments[i]);
				}

				console.log("call " + arguments[0]);
				console.log(args);

				return instance[arguments[0]].apply(instance, args);
			} else {
				return undefined;
			}
		};

		jQuery.fn.extend(obj);
	}
}).methods({
	isExtInstance: function isExtInstance() {
		return true;
	},

	validate: function validate() {
		if (this.config.validate) {
			return this.config.validate.call(this);
		} else {
			return true;
		}
	},

	getValue: function getValue() {
		if (this.config.onGetValue) return this.config.onGetValue.call(this);
		return this.value;
	},

	getOption: function getOption() {
		return this.opt;
	},

	notifyValueChanged: function notifyValueChanged() {
		this.$container.trigger("dxExtValueChanged");
	},

	setValue: function setValue(v) {
		this.value = v;
		this.notifyValueChanged();
		this.render();
	},

	render: function render() {
		this.config.render && this.config.render.call(this, this.$container);
	},

	setAria: function setAria() {
		return undefined;
	},

	option: function option(k, v) {

		if (k === 'value' && v !== undefined) {
			return this.setValue(v);
		} else if (k === 'value') {
			if (this.config.beforeGetValue) {
				this.config.beforeGetValue.call(this);
			}
			return this.getValue();
		}

		if (v === undefined) {
			console.log("query option " + k);

			return this.opt[k];
		} else {
			var orig = this.opt[k];
			this.opt[k] = v;

			if (this.config.onOptionChanged) {
				this.config.onOptionChanged.call(this, {
					option: k,
					value: v,
					oldValue: orig
				});
			}
		}
	},

	element: function element() {
		return this.$container;
	},

	instance: function instance() {
		return this;
	},

	on: function on(evt, fn) {
		var _this = this;

		console.log("on " + evt);

		if (evt === 'valueChanged') {
			this.$container.on("dxExtValueChanged", function () {
				fn.call(_this, {
					component: _this,
					value: _this.value
				});
			});
		}
	},

	reset: function reset() {
		console.log("call reset");
	}
});

DxExtInstance.define({
	name: 'propertyList',
	init: function init($container, option) {},

	render: function render($container) {
		var _this2 = this;

		var _this = this;
		var DATA = this.getValue() || [];

		var te1 = "<div class='row' style='margin-bottom:10px'><div class='col-sm-12' >" + "<div class='pull-left' style='margin-right:30px'><div class='property'></div></div>" + "</div></div>" + "<div class='row ' style='margin-bottom:10px'><div class='col-sm-12 propertydata' >" + "</div></div>";

		var te4 = "<div class='pull-left' ><div class='property_add'></div></div>";

		var post_list = function post_list(ID) {
			console.log(_this2.option);

			$.get($.config('apiUrl') + ("restful/" + ID + "?_model=product-attr-group")).then(function (res) {
				var labels = res.data.labels;
				var formItem = [];

				DATA.forEach(function (it) {
					var form = {
						colCount: 5,
						itemType: 'group',
						items: []
					};

					$.each(labels, function (i, items) {

						var item = {
							label: { text: items.name },
							dataField: "values",
							validationRules: [{
								type: "required",
								message: '请选择' + items.name
							}],
							editorType: 'dxSelectBox',
							editorOptions: {
								dataSource: items.values,
								valueExpr: 'id',
								displayExpr: 'value',
								onValueChanged: function onValueChanged(e) {
									console.log(e);
								}
							}
						};

						form['items'].push(item);
					});

					var origin_price = [{
						label: { text: '原价' },
						dataField: "origin_price",
						value: it.origin_price,
						validationRules: [{
							type: "required",
							message: '请输入原价'
						}]

					}, {
						label: { text: '促销价' },
						dataField: "price",
						value: it.price,
						validationRules: [{
							type: "required",
							message: '请输入促销价'
						}]
					}, {
						label: { text: '库存' },
						dataField: "sku",
						value: it.sku,
						validationRules: [{
							type: "required",
							message: '请输入库存'
						}]
					}, {
						editorType: 'dxButton',
						editorOptions: {
							text: '删除',
							onClick: function onClick() {}
						}
					}];

					form['items'] = form['items'].concat(origin_price);

					formItem.push(form);
				});

				console.log(formItem);
				$container.find('.propertydata').dxForm({
					showColonAfterLabel: true,
					showValidationSummary: false,
					validationGroup: "crud",
					alignItemLabels: true,
					alignItemLabelsInAllGroups: true,
					items: formItem
				});

				$container.find('.property_add').dxButton({
					text: "增加",
					onClick: function onClick() {
						var post_data = {
							origin_price: '',
							price: '',
							sku: '',
							labels: []
						};
						var label = {
							value: ''
						};
						labels.forEach(function (its) {
							post_data['labels'].push(label['attr_label_id'] = its.id);
						});
						_this.setValue(DATA.push(post_data));
						post_list(ID);
					}
				});
			});
		};

		$container.css({ padding: '10px 0' });

		var te3 = "<div class='row' style='margin-bottom:10px'><div class='property_list'></div></div>" + te1 + te4;

		$container.html(te3);

		$container.find('.property_list').dxSelectBox({
			dataSource: $.crudStore(API('restful?_model=product-attr-group')),
			displayExpr: 'name',
			valueExpr: 'id',
			onValueChanged: function onValueChanged(e) {
				var ID = e.value;

				post_list(ID);
			}

		});
	}
});

DxExtInstance.define({
	name: 'imagesdetail',
	init: function init($container, option) {
		var _this = this;

		option = $.extend({}, {
			single: false
		}, option);
		console.log(option);
		$container.css({ padding: '10px 0' });
		$container.html("<div class='images'></div><div class='file image-uploader'></div>");

		var labelText = '';
		if (option.labelText) {
			labelText = option.labelText;
		} else if (option.imageWidth && option.imageHeight) {
			labelText = '建议宽高比是' + option.imageWidth + 'px x ' + option.imageHeight + 'px。';
		}

		$container.find(".file").dxFileUploader({
			selectButtonText: "上传",
			labelText: labelText,
			name: 'file',
			accept: "image/*",
			uploadMode: "instantly",
			uploadUrl: $.config('apiUrl') + "file-upload",
			onUploaded: function onUploaded(e) {
				var pat = JSON.parse(e.request.response).data;

				var value = _this.getValue();

				if (!value) {
					value = option.single ? "" : [];
				};
				console.log(value);
				if (option.single) {
					value = pat.imgSrv;
				} else {
					value.push(pat.imgSrv);
				}
				console.log(value);

				_this.setValue(value);
			}
		});

		// $container.find(".file .dx-button-content").html('<i class="iconfont">&#xe623;</i>');
	},

	render: function render($container) {
		// function imageUrl(url) {
		// 	if(!url.match(/imageView2/)) {
		// 		url += "?imageView2/1/w/100/h/57";
		// 	}

		// 	return url;
		// }

		var _this = this,
		    value = this.getValue();

		var $images = $container.find(".images");
		$images.html("");

		if (value) {
			var option = this.getOption();

			if (option.single) value = [value];
			console.log(option);
			$.each(value, function (i, dat) {
				$("<div>").append($("<img>").attr("src", dat)).append($("<span>").text("删除").click(function () {

					if (!option.single) {
						value.splice(i, 1);
						_this.setValue(value);
					} else {
						value = "";
						_this.setValue(value);
					}

					$(this).parent().remove();
				})).appendTo($images);
			});
		}
	}
});

DxExtInstance.define({
	name: 'ImageUploader',
	init: function init($container, option) {
		var _this = this;

		option = $.extend({}, {
			single: false
		}, option);

		$container.css({ padding: '10px 0' });
		$container.html("<div class='images'></div><div class='file image-uploader'></div>");

		var labelText = '';
		if (option.labelText) {
			labelText = option.labelText;
		} else if (option.imageWidth && option.imageHeight) {
			labelText = '建议宽高比是' + option.imageWidth + 'px x ' + option.imageHeight + 'px。';
		}

		$container.find(".file").dxFileUploader({
			selectButtonText: "上传",
			labelText: labelText,
			name: 'file',
			accept: "image/*",
			uploadMode: "instantly",
			uploadUrl: $.config('apiUrl') + "file-upload",
			onUploaded: function onUploaded(e) {
				var pat = JSON.parse(e.request.response).data;

				var value = _this.getValue();

				if (value === undefined) {
					value = option.single ? "" : [];
				};

				if (option.single) {
					value = pat.imgSrv;
				} else {
					value.push(pat);
				}

				_this.setValue(value);
			}
		});

		// $container.find(".file .dx-button-content").html('<i class="iconfont">&#xe623;</i>');
	},

	render: function render($container) {
		function imageUrl(url) {
			if (!url.match(/imageView2/)) {
				url += "?imageView2/1/w/100/h/57";
			}

			return url;
		}

		var _this = this,
		    value = this.getValue();

		var $images = $container.find(".images");
		$images.html("");

		if (value) {
			var option = this.getOption();

			if (option.single) value = [value];

			$.each(value, function (i, dat) {
				$("<div>").append($("<img>").attr("src", imageUrl(option.single ? dat : dat.imgSrv))).append($("<span>").text("删除").click(function () {

					if (!option.single) {
						value.splice(i, 1);
						_this.setValue(value);
					} else {
						value = "";
						_this.setValue(value);
					}

					$(this).parent().remove();
				})).appendTo($images);
			});
		}
	}
});

DxExtInstance.define({
	name: 'VideoUploader',
	init: function init($container, option) {
		var _this = this;

		option = $.extend({}, {
			single: false
		}, option);

		$container.html("<div class='video-url'></div><div class='file'></div>");

		$container.find(".file").dxFileUploader({
			selectButtonText: "上传",
			labelText: '',
			name: 'file',
			accept: "video/mp4,video/x-m4v,video/*",
			uploadMode: "instantly",
			uploadUrl: $.config('apiUrl') + "file-upload",
			onUploaded: function onUploaded(e) {
				var pat = JSON.parse(e.request.response).data;

				_this.setValue(pat.imgSrv);
			}
		});

		$container.find(".video-url").dxTextBox({
			onValueChanged: function onValueChanged(e) {
				_this.setValue(e.value);
			},
			placeholder: '视频地址'
		});
	},
	render: function render($container) {
		var v = $container.find(".video-url").dxTextBox("option", "value");
		if (v != this.getValue()) {
			$container.find(".video-url").dxTextBox("option", "value", this.getValue());
		}
	}
});

DxExtInstance.define({
	name: 'GrapeList',
	init: function init($container, option) {},
	render: function render($container) {
		var v = this.getValue(),
		    _this = this;

		v = v || [];

		var tpl = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="line-height: 36px; margin-right: 10px;">葡萄</div>' + '<div class="pull-left"><div class="grape-input-name"></div></div>' + '<div class="pull-left" style="line-height: 36px; margin: 0 10px;">种植面积占比</div>' + '<div class="pull-left"><div class="grape-input-area"></div></div>' + '<div class="pull-left" style="line-height: 36px; margin-left: 20px;"><div class="grape-remove"></div>' + '</div></div>';

		$container.html('');
		$.each(v, function (i, item) {
			var $c = $(tpl);

			$c.find(".grape-input-name").dxTextBox({
				width: 200,
				value: item.name,
				onValueChanged: function onValueChanged(e) {
					v[i].name = e.value;
				}
			});

			$c.find(".grape-input-area").dxNumberBox({
				width: 80,
				value: item.proportion,
				showSpinButtons: true,
				// format: "#0%",
				onValueChanged: function onValueChanged(e) {
					v[i].proportion = e.value;
				}
			});

			$c.find(".grape-remove").dxButton({
				text: '删除',
				onClick: function onClick() {
					v.splice(i, 1);
					_this.setValue(v);
				}
			});

			$c.appendTo($container);
		});

		$("<div/>").dxButton({
			text: '增加',
			onClick: function onClick() {
				v.push({
					name: '',
					area: 0
				});
				_this.setValue(v);
			}
		}).appendTo($container);
	}
});

DxExtInstance.define({
	name: 'GrapeDeployList',

	validate: function validate() {
		try {
			var result = DevExpress.validationEngine.validateGroup(this.validationGroup);
			if (result.isValid) {
				var value = this.getValue(),
				    err = false;
				value = value || [];

				this.opt.isValid = false;
				this.opt.validationError = "";

				if (this.opt.mode === 'single') {} else if (this.opt.mode === 'blend') {
					var total = 0;
					$.each(value, function (i, v) {
						total += parseFloat(v.scale);
					});

					if (value.length < 2) {
						err = '至少配置两种葡萄';
					} else if (total > 100) {
						err = '比例设置超过100';
					}
				} else {}

				if (!err) {
					this.opt.isValid = true;
				} else {
					this.opt.validationError = err;
				}
			}

			this.setValue(value);
		} catch (e) {
			this.opt.isValid = false;
		}

		return this.opt.isValid;
	},

	init: function init($container, option) {
		this.opt.mode = this.opt.mode || 'single';
		this.validationGroup = 'GrapeDeployList-' + Math.floor(Math.random() * 1000);

		console.log("init GrapeDeployList");

		// this.setValue(null);
	},

	render: function render($container) {
		var v = this.getValue(),
		    _this = this;

		v = v || [];

		var validationGroup = this.validationGroup;
		var vtpl = '<div class="dx-ex-validation-error"></div>';
		var tpl = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="line-height: 36px; margin-right: 10px;">葡萄</div>' + '<div class="pull-left"><div class="grape-input-name"></div></div>' + '<div class="pull-left" style="line-height: 36px; margin: 0 10px;">采收时间</div>' + '<div class="pull-left"><div class="grape-input-time"></div></div>' + (this.opt.mode === 'blend' ? '<div class="pull-left" style="line-height: 36px; margin: 0 10px;">比例</div>' + '<div class="pull-left"><div class="grape-input-area"></div></div>' + '<div class="pull-left" style="line-height: 36px; margin-left: 20px;"><div class="grape-remove"></div></div>' : '') + '</div></div>';

		$container.html('');

		if (!this.opt.isValid && this.opt.validationError) {
			$('<div class="dx-ex-validation-error">' + this.opt.validationError + '</div>').appendTo($container);
		}

		$.each(v, function (i, item) {
			var $c = $(tpl);

			$c.find(".grape-input-name").dxTextBox({
				width: 200,
				value: item.name,
				onValueChanged: function onValueChanged(e) {
					v[i].name = e.value;
				}
			}).dxValidator({
				validationGroup: validationGroup,
				validationRules: [{
					type: 'required'
				}]
			});

			if (_this.opt.mode === 'blend') {
				$c.find(".grape-input-area").dxNumberBox({
					width: 80,
					value: item.scale,
					showSpinButtons: true,
					// format: "#0%",
					onValueChanged: function onValueChanged(e) {
						v[i].scale = e.value;
					}
				}).dxValidator({
					validationGroup: validationGroup,
					validationRules: [{
						type: 'required'
					}]
				});
			}

			$c.find('.grape-input-time').dxDateBox({
				value: item.harvestDate,
				type: "date",
				displayFormat: 'yyyy-MM-dd',
				dateSerializationFormat: "yyyy-MM-dd",
				onValueChanged: function onValueChanged(e) {
					v[i].harvestDate = e.value;
				}
			});

			$c.find(".grape-remove").dxButton({
				text: '删除',
				onClick: function onClick() {
					v.splice(i, 1);
					_this.setValue(v);
				}
			});

			$c.appendTo($container);
		});

		if (this.opt.mode === 'blend') {
			$("<div/>").dxButton({
				text: '增加',
				onClick: function onClick() {
					v.push({
						name: '',
						scale: 100,
						harvestDate: null
					});
					_this.setValue(v);
				}
			}).appendTo($container);
		}

		if (v.length == 0) {
			$container.html('未选择调配类型');
		}
	},

	onOptionChanged: function onOptionChanged(e) {
		if (e.option === 'mode') {
			var value = this.getValue();

			this.opt.isValid = true;
			this.opt.validationError = "";

			if (value) {
				if (e.value === 'single') {
					if (value.length >= 1) {
						value = value.slice(0, 1);
					} else {
						value.push({
							name: '',
							scale: 100
						});
					}
				} else if (e.value === 'blend') {
					value = value.slice(0, 20);

					while (value.length < 2) {
						value.push({
							name: '',
							scale: 0
						});
					}
				}

				this.setValue(value);
			} else {
				if (e.value === 'single') {
					value = [{
						name: '',
						scale: 100
					}];
				} else if (e.value === 'blend') {
					value = [];

					while (value.length < 2) {
						value.push({
							name: '',
							scale: 0
						});
					}
				}

				this.value = value;
				this.render();
			}
		} else if (e.option === 'isValid') {} else if (e.option === 'validationError') {}
	}
});

DxExtInstance.define({
	name: 'dxEditor',
	init: function init($container, option) {

		var _this = this;
		option = $.extend({}, {
			single: false
		}, option);

		$container.html('<div contenteditable="true" class="ckeditor"></div>');

		// editorH1 editorH3

		// CKEDITOR.basePath = '../libs/ckeditor/';
		this.editor = CKEDITOR.replace($container.find('.ckeditor')[0], {
			extraPlugins: 'uploadimage,simpleimage,wine',
			height: 300,
			allowedContent: true,

			// Upload images to a CKFinder connector (note that the response type is set to JSON).
			uploadUrl: $.config('apiUrl') + "file-upload",

			// Load the default contents.css file plus customizations for this sample.
			contentsCss: [CKEDITOR.basePath + 'contents.css']
		});

		this.editor.setData("", {
			internal: true,
			noSnapshot: true
		});

		this.editor.on("change", function (evt) {
			_this.setValue(_this.editor.getData());
		});

		this.editor.on("notificationHide", function (evt) {
			_this.setValue(_this.editor.getData());
		});

		this.editor.on("wine.insert", function (evt) {
			var editor = _this.editor;

			$("<div>").appendTo($("body")).dxPopup({
				title: '请选择葡萄酒',
				visible: true,
				width: 400,
				height: 200,
				onContentReady: function onContentReady(e) {
					var $content = e.component.content();

					var instance = $(".select-wine").dxSelectBox({
						dataSource: $.crudStore(API("restful?_model=wine-product")),
						searchEnabled: true,
						valueExpr: 'id',
						itemTemplate: function itemTemplate(data, index, $el) {
							if (data) {
								$("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
							}
						},
						displayExpr: function displayExpr(data) {
							return data ? data.chname + " (" + data.name + ")" : "";
						}
					}).dxSelectBox('instance');

					$(".toolbar", $content).dxToolbar({
						items: [{
							location: 'after',
							widget: 'dxButton',
							options: {
								type: 'success',
								text: '确定',
								onClick: function onClick() {
									var v = instance.option('value');
									if (v) {
										editor.insertHtml("<p>{{drink:" + v + "}}</p>");
									}
									e.component.hide();
								}
							}
						}, {
							location: 'after',
							widget: 'dxButton',
							options: {
								type: 'normal',
								text: '取消',
								onClick: function onClick() {
									e.component.hide();
								}
							}
						}]
					});
				},
				contentTemplate: function contentTemplate(contentElement) {
					$('<div><div class="form-container" style="padding-bottom: 20px;"><div class="select-wine"></div></div><div class="toolbar"></div></div>').appendTo(contentElement);
				}
			});
		});

		this.editor.on("simpleimage.insert", function (evt) {
			var editor = _this.editor;

			$("<input type='file' accept='image/*'/>").click().change(function () {
				var formData = new FormData();

				if (this.files.length > 0) {
					formData.append('file', this.files[0]);

					$.ajax({
						url: $.config('apiUrl') + "file-upload",
						type: "POST",
						data: formData,
						processData: false,
						contentType: false
					}).then(function (resp) {
						if (resp && resp.status === "success") {
							editor.insertHtml("<img src='" + resp.data.imgSrv + "?imageView2/0/h/120'/>");
						} else {
							DevExpress.ui.dialog.alert('文件上传失败', '操作失败');
						}
					});
				}
			});
		});
	},

	render: function render($container) {
		if (this.editor) {
			var html = this.editor.getData();
			if (!html && this.getValue()) {
				var _this = this;
				// 直接调用setData偶尔会失败，原因未知
				var editable = _this.editor.editable();

				if (editable) {
					editable.setData(_this.getValue());
				} else {
					_this.editor.setData(_this.getValue(), {
						internal: true,
						noSnapshot: true,
						callback: function callback() {}
					});
				}
			}
		}
	},

	beforeGetValue: function beforeGetValue() {
		if (this.editor) {
			this.value = this.editor.getData();
			this.notifyValueChanged();
		}
	}
});

DxExtInstance.define({
	name: 'Tfselect',
	init: function init($container, option) {
		var _this = this,
		    itemData = [];
		option = $.extend({}, {
			single: false
		}, option);

		if (option.value) {
			$.each(option.value, function (i, va) {
				$('<div>').append($('<div class="tfselect">').dxSelectBox({
					dataSource: va,
					disabled: true,
					displayExpr: "expert_judges",
					valueExpr: "id",
					deferRendering: false
				})).append($('<div class="tftextarea">').dxTextArea({
					value: va.content
				})).append($('<div class="tfdelete">').dxButton({
					text: '删除',
					type: 'normal'
				})).appendTo($container);
			});
		}

		$container.append($('<div class="tfbutton">').dxButton({
			text: '增加专家鉴',
			type: 'normal',
			onClick: function onClick() {
				$container.find('.tfbutton').before($('<div>').append($('<div>').dxSelectBox({
					dataSource: new DevExpress.data.DataSource({
						store: $.crudStore(API("restful?_model=expert-user"))
					}),
					displayExpr: 'name',
					valueExpr: 'id'

				})).append($('<div>').dxTextArea({})).append($('<div>').dxButton({
					text: '删除',
					type: 'normal'

				})));
			}
		}));
	},
	render: function render($container) {}
});

DxExtInstance.define({
	name: 'Tfexpret',
	init: function init($container, option) {
		var _this = this;
		option = $.extend({}, {
			single: false
		}, option);

		$container.append($("<div>").dxSelectBox({
			dataSource: option.value,
			value: option.value[0].id,
			displayExpr: 'expert_user_name',
			valueExpr: 'id',
			showClearButton: true,
			placeholder: "分类",
			searchEnabled: true,
			noDataText: '没有请求到分类数据',
			deferRendering: false,
			onValueChanged: function onValueChanged(e) {
				_this.setValue(e.value);
			}
		}));
	},
	render: function render($container) {}
});

DxExtInstance.define({
	name: 'Tfscore',
	init: function init($container, option) {
		var _this = this;
		option = $.extend({}, {
			single: false
		}, option);
		var docu = $("<div> <span>专家评分</span> <div class='tfselect' ></div> <span>评分</span> <div class='tftext'></div>   </div>");

		docu.find("span").css({
			"margin": "10px",
			"width": "10%"
		});

		var boxtext = docu.find(".tftext").dxTextBox({}).data("dxTextBox");

		docu.find(".tfselect").dxSelectBox({
			dataSource: option.value,
			displayExpr: "expert_user_name",
			valueExpr: 'score',
			showClearButton: true,
			noDataText: '没有专家评分',
			placeholder: '专家分类',
			onValueChanged: function onValueChanged(e) {
				boxtext.option("value", e.value);
			}
		});

		docu.appendTo($container);
	},
	render: function render($container) {}
});

DxExtInstance.define({
	name: 'Tfsame_score',
	init: function init($container, option) {
		var _this = this;
		option = $.extend({}, {
			single: false
		}, option);
		var docu = $("<div> <span>生产年份</span> <div class='tfselect' ></div> <span>平均分</span> <div class='tftext'></div>   </div>");

		docu.find("span").css({
			"margin": "10px",
			"width": "10%"
		});

		var boxtext = docu.find(".tftext");

		var boxselect = $("<div>").dxSelectBox({
			dataSource: [],
			displayExpr: 'expert_user_name',
			valueExpr: 'expert_user_id',
			showClearButton: true,
			noDataText: '没有数据',
			onSelectionChanged: function onSelectionChanged(e) {}
		});

		docu.find(".tfselect").dxSelectBox({
			dataSource: option.value,
			displayExpr: "vintage",
			valueExpr: 'averageScore',
			showClearButton: true,
			noDataText: '没有同系列酒',
			placeholder: '同系列酒分类',
			value: 'expert_scores',
			onSelectionChanged: function onSelectionChanged(e) {
				console.log(e);
				boxtext.text(e.selectedItem.averageScore);
				boxselect.option('dataSource', e.selectedItem.expert_scores);
			}
		});

		docu.appendTo($container);
		boxselect.appendTo($container);
	},
	render: function render($container) {}
});

DxExtInstance.define({
	name: 'ExpertList',
	init: function init($container, option) {},
	render: function render($container) {
		var v = this.getValue(),
		    _this = this;

		v = v || [];

		var tpl = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="width: 120px; line-height: 36px;">专家/达人</div>' + '<div class="pull-left" style="width: 50%;"><div class="expert-input-name"></div></div>' + '<div class="pull-left" style="line-height: 36px; margin-left: 20px;"><div class="expert-remove"></div></div>' + '</div></div>' + '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="width: 120px; line-height: 36px;">点评内容</div>' + '<div class="pull-left" style="width: 50%;"><div class="expert-input-area"></div></div>' + '</div></div>' + '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="width: 120px; line-height: 36px;">一句话点评</div>' + '<div class="pull-left" style="width: 50%;"><div class="expert-input-word"></div></div>' + '</div></div>;';

		$container.html('');
		$.each(v, function (i, item) {
			var $c = $(tpl);

			$c.find(".expert-input-name").dxSelectBox({
				dataSource: $.crudStore(API('restful?_model=expert-user')),
				showClearButton: true,
				placeholder: "专家",
				searchEnabled: true,
				valueExpr: 'id',
				noDataText: '没有请求到专家数据',
				itemTemplate: function itemTemplate(data, index, $el) {
					if (data) {
						$("<span>" + data.name + " (" + data.account + ")</span>").appendTo($el);
					}
				},
				displayExpr: function displayExpr(data) {
					return data ? data.name + " (" + data.account + ")" : "";
				},
				width: '100%',
				value: item.expert_user_id,
				onValueChanged: function onValueChanged(e) {
					v[i].expert_user_id = e.value;
				}
			});

			$c.find(".expert-input-area").dxTextArea({
				width: '100%',
				value: item.content,
				onValueChanged: function onValueChanged(e) {
					v[i].content = e.value;
				}
			});

			$c.find(".expert-remove").dxButton({
				text: '删除',
				onClick: function onClick() {
					v.splice(i, 1);
					_this.setValue(v);
				}
			});

			$c.find('.expert-input-word').dxTextBox({
				width: '100%',
				value: item.short_review,
				onValueChanged: function onValueChanged(e) {
					v[i].short_review = e.value;
				}
			});

			$c.appendTo($container);
		});

		$("<div/>").dxButton({
			text: '增加',
			onClick: function onClick() {
				v.push({
					expert_user_id: 0,
					content: '',
					short_review: ''
				});
				_this.setValue(v);
			}
		}).appendTo($container);
	}
});

DxExtInstance.define({
	name: 'ExpertScoreList',
	init: function init($container, option) {
		$container.html('<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<h3 class="pull-left score-year-title">本款酒</h3>' + '<div class="score-title pull-left" style="line-height: 36px; margin: 0 10px;">平均分 <span class="avg-score">0</span></div>' + '</div></div>' + '<div class="score-container"></div>');
	},
	render: function render($container) {
		var v = this.getValue(),
		    _this = this,
		    $content = $container.find(".score-container");

		v = v || [];

		var tpl = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="line-height: 36px; margin-right: 10px;">专家</div>' + '<div class="pull-left"><div class="expert-input-name"></div></div>' + '<div class="pull-left" style="line-height: 36px; margin: 0 10px;">评分</div>' + '<div class="pull-left"><div class="expert-input-area"></div></div>' + '<div class="pull-left" style="line-height: 36px; margin-left: 20px;"><div class="expert-remove"></div>' + '</div></div>';

		var updateScore = function updateScore() {
			var v = _this.getValue() || [],
			    s = 0;

			$.each(v, function (i, vitem) {
				var n = parseInt(vitem.score) || 0;
				s += n;
			});

			$(".avg-score", $container).text(v.length > 0 ? Math.ceil(s / v.length) : 0);
		};

		$content.html('');
		$.each(v, function (i, item) {
			var $c = $(tpl);

			$c.find(".expert-input-name").dxSelectBox({
				dataSource: $.crudStore(API('restful?_model=expert-user')),
				showClearButton: true,
				placeholder: "专家",
				searchEnabled: true,
				valueExpr: 'id',
				noDataText: '没有请求到专家数据',
				itemTemplate: function itemTemplate(data, index, $el) {
					if (data) {
						$("<span>" + data.name + " (" + data.account + ")</span>").appendTo($el);
					}
				},
				displayExpr: function displayExpr(data) {
					return data ? data.name + " (" + data.account + ")" : "";
				},
				value: item.expert_user_id,
				onValueChanged: function onValueChanged(e) {
					v[i].expert_user_id = e.value;
				}
			});

			$c.find(".expert-input-area").dxNumberBox({
				width: 80,
				value: item.score,
				showSpinButtons: true,
				// format: "#0%",
				onValueChanged: function onValueChanged(e) {
					v[i].score = e.value;
					updateScore();
				}
			});

			$c.find(".expert-remove").dxButton({
				text: '删除',
				onClick: function onClick() {
					v.splice(i, 1);
					_this.setValue(v);
				}
			});

			$c.appendTo($content);
		});

		$("<div/>").dxButton({
			text: '添加专家评分',
			onClick: function onClick() {
				v.push({
					expert_user_id: 0,
					score: 0
				});
				_this.setValue(v);
			}
		}).appendTo($content);

		updateScore();
	}
});

DxExtInstance.define({
	name: 'ExpertYearScoreList',
	init: function init($container, option) {},
	render: function render($container) {
		var v = this.getValue(),
		    _this = this;
		console.log(v);
		v = v || [];

		var tplH = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<h3 class="pull-left score-year-title">属性</h3>' + '<div class="pull-right"><div class="score-year-remove"></div></div>' + '</div></div>';

		var tpl0 = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="line-height: 36px; margin-right: 10px;">属性名称</div>' + '<div class="pull-left"><div class="score-year"></div></div>' + '</div></div>' + '<div class="score-container"></div>' + '<div style="margin-top: 20px;"><div class="expert-add"></div></div>';

		var tpl = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="line-height: 36px; margin-right: 10px;">属性</div>' + '<div class="pull-left"><div class="expert-input-name"></div></div>' + '<div class="pull-left" style="line-height: 36px; margin-left: 20px;"><div class="expert-remove"></div>' + '</div></div>';

		var updateScore = function updateScore() {
			var v = _this.getValue() || [],
			    s = 0;

			$.each(v, function (i, vitem) {
				var n = parseInt(vitem.score) || 0;
				s += n;
			});

			$(".avg-score", $container).text(v.length > 0 ? Math.ceil(s / v.length) : 0);
		};

		$container.html('');
		$.each(v, function (i, item) {
			var $c0 = $("<div style='margin-bottom: 20px;'>" + tplH + tpl0 + "</div>");

			$c0.find(".score-year-title").text('属性 #' + i);

			$c0.find(".score-year-remove").dxButton({
				text: '删除',
				onClick: function onClick() {
					v.splice(i, 1);
					_this.setValue(v);
				}
			});

			$c0.find(".score-year").dxTextBox({
				value: v[i].name,
				onValueChanged: function onValueChanged(e) {
					v[i].name = e.value;
				}
			});

			var $cc = $c0.find(".score-container");

			if (v[i].values) {

				v[i].values = v[i].values;
				// v[i].values = undefined;
			} else {
				v[i].values = v[i].values || [];
			}

			v[i].type = 'radio';

			$c0.find(".expert-add").dxButton({
				text: '添加属性',
				onClick: function onClick() {
					v[i].values.push({
						value: ''

					});
					_this.setValue(v);
				}
			});

			$.each(item.values, function (k, item) {
				var _$c$find$dxTextBox;

				var $c = $(tpl);

				$c.find(".expert-input-name").dxTextBox((_$c$find$dxTextBox = {
					value: '',
					itemTemplate: function itemTemplate(data, index, $el) {
						if (data) {
							$("<span>" + data.name + " (" + data.account + ")</span>").appendTo($el);
						}
					},
					displayExpr: function displayExpr(data) {
						return data ? data.name + " (" + data.account + ")" : "";
					}
				}, _defineProperty(_$c$find$dxTextBox, "value", item.value), _defineProperty(_$c$find$dxTextBox, "onValueChanged", function onValueChanged(e) {
					v[i].values[k].value = e.value;
				}), _$c$find$dxTextBox));

				// $c.find(".expert-input-area").dxNumberBox({
				// 	width: 80,
				// 	value: item.score,
				// 	showSpinButtons: true,
				// 	// format: "#0%",
				// 	onValueChanged: function(e) {
				// 		v[i].items[k].score = e.value;
				// 		updateScore();
				// 	}
				// });

				$c.find(".expert-remove").dxButton({
					text: '删除',
					onClick: function onClick() {
						v[i].values.splice(k, 1);
						_this.setValue(v);
					}
				});

				$c.appendTo($cc);
			});

			$c0.appendTo($container);
		});

		$("<div/>").dxButton({
			text: '添加类',
			onClick: function onClick() {
				v.push({
					name: "",
					values: []
				});
				_this.setValue(v);
			}
		}).appendTo($container);

		updateScore();
	}
});

DxExtInstance.define({
	name: 'YearSelect',
	init: function init($container, option) {
		var years = [],
		    _this = this;
		for (var y = 1950; y <= 2050; y++) {
			years.push(y);
		}$("<div class='year-select'/>").appendTo($container).dxSelectBox({
			dataSource: years,
			acceptCustomValue: true,
			onValueChanged: function onValueChanged(e) {
				_this.setValue(e.value);
			},
			displayExpr: function displayExpr(v) {
				return v ? v + '年' : '';
			}
		});
	},
	render: function render($container) {
		var v = this.getValue(),
		    v0 = $(".year-select", $container).dxSelectBox("option", "value");

		if (v != v0) {
			$(".year-select", $container).dxSelectBox("option", "value", v);
		}
	}
});

var DxExtClass = function () {
	function DxExtClass() {
		_classCallCheck(this, DxExtClass);
	}

	_createClass(DxExtClass, [{
		key: "define",
		value: function define(opt) {
			DxExtInstance.define(opt);
		}
	}, {
		key: "validate",
		value: function validate(formInstance) {
			DxExtInstance.validate(formInstance);
		}
	}]);

	return DxExtClass;
}();

var DxExt = exports.DxExt = new DxExtClass();


},{}],7:[function(require,module,exports){
'use strict';

var _app = require('./app');

var _util = require('./util');

var _util2 = _interopRequireDefault(_util);

var _page = require('./page');

require('./dx-ext');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var orderType = [{ name: '全部类型', id: '' }, { name: '微信订单', id: '1' }, { name: '积分订单', id: '2' }];
var orderState = [{ name: '全部状态', id: '' }, { name: '待支付', id: 0 }, { name: '待发货', id: 1 }, { name: '已取消', id: 2 }, { name: '已发货', id: 5 }, { name: '已完成', id: 6 }, { name: '交易关闭', id: 7 }];

var filterExpr = {},
    searchTextBoxInstance = void 0;
var applyFilterExpr = function applyFilterExpr(ds) {
	var applyFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

	var arr = [];

	if (filterExpr.type) {
		arr.push(['pay_method', '=', filterExpr.type]);
	}

	if (filterExpr.state || filterExpr.state === 0) {
		arr.push(['state', '=', filterExpr.state]);
	}

	if (filterExpr.start) {
		arr.push(['created_at', '>=', filterExpr.start]);
	}

	if (filterExpr.end) {
		arr.push(['created_at', '<=', filterExpr.end]);
	}

	if (applyFilter) {
		return arr;
	};

	if (arr.length) ds.filter(arr);else ds.filter(null);
};

_app.App.registerCrud({
	route: 'order',
	url: $.config('apiUrl') + 'restful?_model=order',
	title: '订单',
	placeholder: '订单号或产品名称',
	capable: {
		create: true
	},
	grid: {
		selection: {
			mode: 'none'
		},
		columnAutoWidth: true,
		showRowLines: true,
		wordWrapEnabled: true
	},
	search: {
		mobile: 'out_trade_no'
	},
	toolbar: {
		items: [{
			location: 'before',
			widget: 'dxTextBox',
			options: {
				width: 300,
				placeholder: '搜索',
				onInitialized: function onInitialized(e) {
					searchTextBoxInstance = e.component;
				}
			}
		}, {
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '查询',
				onClick: function onClick(e) {
					var ds = _app.App.crudGridInstance().option('dataSource');

					ds.searchExpr(['out_trade_no', 'product_name', 'tel_number', 'username', 'create_user.name']);
					ds.searchValue(searchTextBoxInstance.option('value'));

					ds.reload();
				}
			}
		}, {
			location: 'after',
			widget: 'dxSelectBox',
			options: {
				dataSource: orderType,
				valueExpr: 'id',
				displayExpr: 'name',
				value: orderType[0].id,
				onValueChanged: function onValueChanged(e) {
					var ds = _app.App.crudGridInstance().option('dataSource');

					filterExpr.type = e.value;
					applyFilterExpr(ds);

					ds.reload();
				}
			}
		}, {
			location: 'after',
			widget: 'dxSelectBox',
			options: {
				dataSource: orderState,
				valueExpr: 'id',
				displayExpr: 'name',
				value: orderState[0].id,
				onValueChanged: function onValueChanged(e) {
					var ds = _app.App.crudGridInstance().option('dataSource');

					filterExpr.state = e.value;
					applyFilterExpr(ds);

					ds.reload();
				}
			}
		}, {
			location: 'after',
			widget: 'dxDateBox',
			options: {
				displayFormat: "yyyy-MM-dd",
				dateSerializationFormat: 'yyyy-MM-dd',
				placeholder: '开始时间',
				onValueChanged: function onValueChanged(e) {
					var ds = _app.App.crudGridInstance().option('dataSource');

					filterExpr.start = e.value;
					applyFilterExpr(ds);

					ds.reload();
				}
			}
		}, {
			location: 'after',
			widget: 'dxDateBox',
			options: {
				displayFormat: "yyyy-MM-dd",
				dateSerializationFormat: 'yyyy-MM-dd',
				placeholder: '结束时间',
				onValueChanged: function onValueChanged(e) {
					var ds = _app.App.crudGridInstance().option('dataSource');

					filterExpr.end = e.value;
					applyFilterExpr(ds);

					ds.reload();
				}
			}
		}, {
			location: 'after',
			widget: 'dxButton',
			options: {
				text: '导出',
				onClick: function onClick(e) {
					var ds = _app.App.crudGridInstance().option('dataSource');
					var url = new Url(API('order-export'));
					var loadOptions = { desc: true, filter: applyFilterExpr(ds, true) };

					url.query._param = JSON.stringify(loadOptions);

					window.location = url;

					// $.crudStore(API('order-export')).load({desc:true,filter:applyFilterExpr(ds,true)}).then(res=>{
					// 	console.log(res)
					// })


					// let apply=applyFilterExpr(ds).concat({desc:true});
					// console.log(apply)
					// $.get(API('order-export'),apply,function(res){
					// 	console.log(res)
					// })
				}
			}
		}]
	},
	columns: [{
		dataField: 'out_trade_no',
		caption: '订单号'
	}, {
		dataField: 'create_user.name',
		caption: '付款人'
	}, {
		dataField: 'product_name',
		caption: '产品名称'
	}, {
		dataField: 'total_fee',
		caption: '总金额'
	}, {
		dataField: 'quantity',
		caption: '数量'
	}, {
		dataField: 'pay_method',
		caption: '支付方式',
		cellTemplate: function cellTemplate(c, e) {
			$(c).text(e.value === 1 ? '微信支付' : '积分兑换');
		}
	}, {
		dataField: 'username',
		caption: '收货人'
	}, {
		dataField: 'tel_number',
		caption: '手机号'
	}, {
		dataField: 'address',
		caption: '地址'
	}, {
		dataField: 'state',
		caption: '状态',
		cellTemplate: function cellTemplate(c, e) {
			var text = orderState.filter(function (item) {
				return item.id == e.value && item.id !== '';
			});
			if (text.length != 0) $(c).text(text[0].name);
		}
	}, {
		dataField: 'created_at',
		caption: '下单时间'
	}, {
		dataField: '	state',
		allowSorting: false,
		caption: '发货',
		cellTemplate: function cellTemplate(c, e) {
			var logistics = {
				out_trade_no: e.data.out_trade_no
			};
			function active() {
				$.post(API('order-delivery'), logistics, function (e) {
					DevExpress.ui.notify('发货成功', 'success', 1500);
					_app.App.crudGridInstance().option('dataSource').load();
				});
				return false;
			};

			if (e.data.state == '1') {
				$("<a>").text('发货').css({ "text-decoration": "underline" }).click(function () {
					active();
				}).appendTo(c);
			}
		}
	}]
});


},{"./app":2,"./dx-ext":6,"./page":8,"./util":11}],8:[function(require,module,exports){
"use strict";

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Page = exports.Page = function () {
	function Page($container) {
		_classCallCheck(this, Page);

		this.$container = $container;
		this.$content = $container;
	}

	_createClass(Page, [{
		key: "crudLayout",
		value: function crudLayout(opt) {
			var data = $.extend({ title: '未设置' }, opt),
			    html = "<div class=\"app-content-body \">\n\t\t  <div class=\"bg-light lter b-b wrapper-md hidden-print\">\n\t\t    <h1 class=\"m-n font-thin h3\">{{title}}</h1>\n\t\t  </div>\n\t\t  <div>\n\t\t    <div class=\"crud-container crud-reset\">\n\t\t    </div>\n\t\t  </div>\n\t\t</div>";

			this.$container.html(Mustache.render(html, data));
			this.$content = this.$container.find(".crud-container");

			return this;
		}
	}, {
		key: "content",
		get: function get() {
			return this.$content;
		}
	}]);

	return Page;
}();


},{}],9:[function(require,module,exports){
'use strict';

var _app = require('./app');

var _util = require('./util');

var _util2 = _interopRequireDefault(_util);

var _page = require('./page');

var _dxExt = require('./dx-ext');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

_dxExt.DxExt.define({
  name: 'DealerInput',
  init: function init($container, option) {
    var _this = this;

    option = $.extend({}, {
      single: false
    }, option);

    $container.html("<div class='tagbox'></div><div style='margin-top: 20px;' class='grid'></div>");

    this.tagBoxInstance = $container.find(".tagbox").dxTagBox({
      deferRendering: false,
      dataSource: $.crudStore(API("restful?_model=sys-dealer")),
      searchEnabled: true,
      valueExpr: 'id',
      displayExpr: 'name',
      placeholder: '请选择经销商',
      onSelectionChanged: function onSelectionChanged(e) {
        var v = _this.getValue() || [],
            changed = false;

        e.addedItems.forEach(function (x) {
          var idx = v.findIndex(function (y) {
            return y.id == x.id;
          });
          if (idx < 0) {
            v.push({ id: x.id, show: 0, name: x.name });
            changed = true;
          }
        });

        var len = v.length;
        e.removedItems.forEach(function (x) {
          return v = v.filter(function (it) {
            return x.id !== it.id;
          });
        });
        if (!changed && len != v.length) changed = true;

        if (changed) setTimeout(function () {
          return _this.setValue(v);
        }, 0);
      }
    }).dxTagBox("instance");

    this.gridInstance = $container.find(".grid").dxDataGrid({
      columns: [{
        dataField: 'name',
        caption: '名称'
      }, {
        dataField: 'show',
        width: 120,
        caption: '是否显示',
        cellTemplate: function cellTemplate(c, ci) {
          var $el = $("<a>");
          $el.css("text-decoration", "underline").text(ci.value ? "显示" : "不显示").attr('title', '单击切换').appendTo(c);
          $el.click(function () {
            var v = _this.getValue() || [],
                idx = v.findIndex(function (x) {
              return x.id == ci.data.id;
            });

            if (idx >= 0) {
              v[idx].show = v[idx].show == 0 ? 1 : 0;
              _this.setValue(v);
            }
          });
        }
      }, {
        width: 120,
        dataField: 'id',
        caption: '删除',
        cellTemplate: function cellTemplate(c, ci) {
          var $el = $("<a>");
          $el.css("text-decoration", "underline").text("删除").appendTo(c);
          $el.click(function () {
            var v = _this.getValue() || [],
                idx = v.findIndex(function (x) {
              return x.id == ci.value;
            });

            if (idx >= 0) {
              v.splice(idx, 1);
              _this.setValue(v);
            }
          });
        }
      }]
    }).dxDataGrid("instance");

    // $container.find(".file .dx-button-content").html('<i class="iconfont">&#xe623;</i>');
  },

  render: function render($container) {
    var v = this.getValue() || [];

    if (this.gridInstance) {
      this.gridInstance.option('dataSource', v);
    }

    if (this.tagBoxInstance) {
      this.tagBoxInstance.option('value', v.map(function (item) {
        return item.id;
      }));
    }

    // if ($container.find(".grid").length > 0) {
    //   $container.find(".grid").dxDataGrid('option', 'dataSource', v);
    // }
  }
});

function validateForm(formInstance) {
  console.log('validateForm');

  var editors = [];

  function _check(o) {
    if (o.dataField) {
      var editor = formInstance.getEditor(o.dataField);
      if (editor && typeof editor.isExtInstance === 'function') {
        editors.push(editor);
      }
    } else if (o.items) {
      $.each(o.items, function (i, item) {
        _check(item);
      });
    }
  }

  _check({
    items: formInstance.option('items')
  });

  var result = true;
  $.each(editors, function (i, e) {
    if (!e.validate()) {
      result = false;
    }
  });

  return result;
}

_dxExt.DxExt.define({
  name: 'dxScene',

  init: function init($container, option) {
    var sceneByLevel = {
      "1": [],
      "2": [],
      "3": []
    };

    function _tr(items, level) {
      for (var i = 0; i < items.length; i++) {
        sceneByLevel[level.toString()].push(items[i]);

        if (items[i].child && items[i].child.length > 0) {
          _tr(items[i].child, level + 1);
        }
      }
    }

    _tr(this.opt.sceneTree, 1);

    this.sceneByLevel = sceneByLevel;
  },

  render: function render($container) {
    var _this2 = this;

    var v = this.getValue(),
        _this = this;

    v = v || [];

    $container.html('');

    var tpl = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left"><div class="grape-input-one" style="margin-right: 10px;"></div></div>' + '<div class="pull-left"><div class="grape-input-two" style="margin-right: 10px;"></div></div>' + '<div class="pull-left"><div class="grape-input-three" style="margin-right: 10px;"></div></div>' + '<div class="pull-left" style="margin-right: 10px;"><div class="remove-item"></div></div>' + '</div></div>';

    var lookupItem = function lookupItem(v, items) {
      var idx = items.findIndex(function (it) {
        return it.value == v;
      });

      return idx >= 0 ? items[idx] : null;
    };

    var arrayOrEmpty = function arrayOrEmpty(item) {
      return item ? [item] : [];
    };

    console.log('dxScene value');
    console.log(v);

    $.each(v, function (i, item) {
      var $tpl = $(tpl);

      $tpl.find(".grape-input-one").dxSelectBox({
        dataSource: _this2.sceneByLevel["1"],
        displayExpr: 'name',
        valueExpr: 'value',
        value: parseInt(item.scene_one_id),
        onValueChanged: function onValueChanged(e) {
          v[i].scene_one_id = e.value;

          var item = lookupItem(e.value, _this.sceneByLevel["1"]);
          $tpl.find(".grape-input-two").dxSelectBox('instance').option('dataSource', item ? item.child : []);

          $tpl.find('.grape-input-three').dxSelectBox('instance').option('dataSource', []);
        }
      });

      $tpl.find(".grape-input-two").dxSelectBox({
        dataSource: arrayOrEmpty(lookupItem(item.scene_two_id, _this.sceneByLevel["2"])),
        displayExpr: 'name',
        valueExpr: 'value',
        value: parseInt(item.scene_two_id),
        onValueChanged: function onValueChanged(e) {
          v[i].scene_two_id = e.value;

          var item = lookupItem(e.value, _this.sceneByLevel["2"]);
          $tpl.find(".grape-input-three").dxSelectBox('instance').option('dataSource', item ? item.child : []);
        }
      });

      $tpl.find(".grape-input-three").dxSelectBox({
        dataSource: arrayOrEmpty(lookupItem(item.scene_three_id, _this.sceneByLevel["3"])),
        displayExpr: 'name',
        valueExpr: 'value',
        value: parseInt(item.scene_three_id),
        onValueChanged: function onValueChanged(e) {
          v[i].scene_three_id = e.value;
        }
      });

      $tpl.find(".remove-item").dxButton({
        text: '删除',
        onClick: function onClick() {
          v.splice(i, 1);
          _this.setValue(v);
        }
      });

      $tpl.appendTo($container);
    });

    $("<div/>").dxButton({
      text: '增加',
      onClick: function onClick() {
        v.push({ scene_one_id: 0, scene_two_id: 0, scene_three_id: 0 });
        _this.setValue(v);
      }
    }).appendTo($container);
  }
});

_dxExt.DxExt.define({
  name: 'dxTasteList',

  init: function init($container, option) {
    // this.setValue(null);
    this.store = $.crudStore(API('restful?_model=wine-cuisine'));
  },

  render: function render($container) {
    var v = this.getValue(),
        _this = this;

    v = v || [];

    var tpl = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="margin-right:30px"><div class="grape-input-taste"></div></div>' + '<div class="pull-left" style="margin-right:30px"><div class="grape-input-remark"></div></div>' + '<div class="pull-left" style="margin-right:30px"><div class="grape-remove"></div></div>' + '</div></div>';

    $container.html('');

    $.each(v, function (i, item) {
      var $c = $(tpl);

      $c.find(".grape-input-taste").dxSelectBox({
        dataSource: _this.store,
        width: 200,
        value: item.wine_cuisines_id,
        valueExpr: 'id',
        displayExpr: 'name',
        onValueChanged: function onValueChanged(e) {
          v[i].wine_cuisines_id = e.value;
        }
      });

      $c.find('.grape-input-remark').dxTextBox({
        width: 400,
        value: item.text,
        onValueChanged: function onValueChanged(e) {
          v[i].text = e.value;
        }
      });

      $c.find(".grape-remove").dxButton({
        text: '删除',
        onClick: function onClick() {
          v.splice(i, 1);
          _this.setValue(v);
        }
      });

      $c.appendTo($container);
    });

    $("<div/>").dxButton({
      text: '增加',
      onClick: function onClick() {
        v.push({
          wine_cuisines_id: 0,
          text: ''
        });
        _this.setValue(v);
      }
    }).appendTo($container);
  }
});

_dxExt.DxExt.define({
  name: 'dxUserLabel',

  init: function init($container, option) {},

  render: function render($container) {
    var v = this.getValue(),
        _this = this;

    v = v || [];

    var tpl = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="line-height: 36px; margin-right: 10px;">身份</div>' + '<div class="pull-left" style="margin-right: 10px;"><div class="grape-input-name"></div></div>' + '<div class="pull-left" style="line-height: 36px; margin-right: 10px;">性别</div>' + '<div class="pull-left"  style="margin-right: 10px;"><div class="grape-input-sex"></div></div>' + '<div class="pull-left" style="line-height: 36px; margin-right: 10px;">年龄段</div>' + '<div class="pull-left" style="margin-right: 10px;"><div class="grape-input-age"></div></div>' + '<div class="pull-left"><div class="grape-remove"></div></div>' + '</div></div>';

    $container.html('');

    var age = ['18-25', '25-30', '30-35', '35-45', '45-55', '55以上'];
    var auth = ['领导', '客户', '长辈', '闺蜜', '基友', '朋友', '情侣'];

    $.each(v, function (i, item) {
      var $c = $(tpl);

      $c.find(".grape-input-name").dxSelectBox({
        dataSource: auth,
        width: 200,
        value: item.auth,
        onValueChanged: function onValueChanged(e) {
          v[i].auth = e.value;
        }
      });

      $c.find('.grape-input-sex').dxSelectBox({
        width: 200,
        dataSource: [{ text: '男', value: 'man' }, { text: '女', value: 'woman' }],
        valueExpr: 'value',
        displayExpr: 'text',
        value: item.sex,
        onValueChanged: function onValueChanged(e) {
          v[i].sex = e.value;
        }
      });

      $c.find('.grape-input-age').dxSelectBox({
        width: 200,
        dataSource: age,
        value: item.age,
        onValueChanged: function onValueChanged(e) {
          console.log(e);
          v[i].age = e.value;
        }
      });

      $c.find(".grape-remove").dxButton({
        text: '删除',
        onClick: function onClick() {
          v.splice(i, 1);
          _this.setValue(v);
        }
      });

      $c.appendTo($container);
    });

    $("<div/>").dxButton({
      text: '增加',
      onClick: function onClick() {
        v.push({ auth: '', sex: '', age: '' });
        _this.setValue(v);
      }
    }).appendTo($container);
  }
});

_dxExt.DxExt.define({
  name: 'KeywordList',

  init: function init($container, option) {
    // this.setValue(null);
    this.store = $.crudStore(API('restful?_model=wine-taste-keywords'));
  },

  render: function render($container) {
    var v = this.getValue(),
        _this = this;

    v = v || [];

    var tpl = '<div class="row" style="margin-bottom: 10px;"><div class="col-sm-12">' + '<div class="pull-left" style="margin-right:30px"><div class="grape-input-taste"></div></div>' + '<div class="pull-left" style="margin-right:30px"><div class="grape-input-remark"></div></div>' + '<div class="pull-left" style="margin-right:30px"><div class="grape-remove"></div></div>' + '</div></div>';

    $container.html('');

    $.each(v, function (i, item) {
      var $c = $(tpl);

      $c.find(".grape-input-taste").dxSelectBox({
        dataSource: _this.store,
        width: 200,
        value: item.keyword_id,
        valueExpr: 'id',
        displayExpr: 'name',
        onValueChanged: function onValueChanged(e) {
          v[i].keyword_id = e.value;
        }
      });

      $c.find('.grape-input-remark').dxTextBox({
        width: 400,
        value: item.text,
        onValueChanged: function onValueChanged(e) {
          v[i].text = e.value;
        }
      });

      $c.find(".grape-remove").dxButton({
        text: '删除',
        onClick: function onClick() {
          v.splice(i, 1);
          _this.setValue(v);
        }
      });

      $c.appendTo($container);
    });

    $("<div/>").dxButton({
      text: '增加',
      onClick: function onClick() {
        v.push({
          keyword_id: 0,
          text: ''
        });
        _this.setValue(v);
      }
    }).appendTo($container);
  }
});

var initPage = function initPage(context, $container) {
  var page = new _page.Page($container);

  var id = context.params.id,
      wineStore = $.crudStore(API("restful?_model=product"));
  var formData = '',
      data = {};

  page.crudLayout({ title: id ? '编辑' : '新建' });

  page.content.html('\n    <form id="form-container">\n      <div class="form_title">\n        <div class="my_hd" style="padding: 0; border-bottom: 0;">\n          <div id="dxtabs"></div>\n        </div>\n        <div class="crud-container crud-reset">\n\t        <div class="row">\n\t          <div class="col-sm-12">\n\t            \n\t            <div id="wine-form">\n\t            </div>\n\t          </div>\n\t        </div>\n\t      \t\n\t      \t<div class="row">\n\t\t        <div class="col-sm-12 text-right" style="margin-top: 15px;">\n\t\t          <div id=\'saveData\'></div>\n\t\t          <div id="cancel"></div>\n\t\t        </div>\n\t      \t</div>\n        </div>\n\t  \t</div>\n    </form>\n\t');

  $(".main-title").text(id ? "编辑葡萄酒信息" : "新建葡萄酒信息");

  var xhrs = [],
      prefetchData = {},
      formInstances = {};

  xhrs.push($.get(API("restful?_model=product")).then(function (resp) {
    prefetchData['restful?_model=product'] = resp.data;
  }));

  xhrs.push($.get(API('restful?_model=product-attr-group')).then(function (resp) {
    prefetchData['restful?_model=product-attr-group'] = resp;
  }));

  $.when.apply($, xhrs).then(function () {
    var formItems = {};

    formItems['show'] = [{
      dataField: 'keywords',
      label: { text: '产品名称' },
      editorType: 'KeywordList',
      editorOptions: {}
    }, {
      dataField: 'consume',
      label: { text: '消费指南' },
      editorType: 'dxTextArea'
    }, {
      itemType: 'group',
      colCount: '3',
      items: [{
        dataField: 'wineglass',
        label: { text: '杯形' }
      }, {
        dataField: 'sober_time',
        label: { text: '醒酒时间' }
      }, {
        dataField: 'temperature',
        label: { text: '饮用温度' }
      }]
    }, {
      itemType: 'group',
      items: [{
        dataField: 'chinese_food',
        label: { text: '中餐搭配' }

      }, {
        dataField: 'western_food',
        label: { text: '西餐搭配' }
      }, {
        dataField: 'snack',
        label: { text: '小食搭配' }
      }, {
        dataField: 'undelicacy',
        label: { text: '暗黑搭配' }
      }]
    }, {
      dataField: 'talk_keywords',
      label: { text: '谈资关键词' },
      helpText: '20字内'
    }, {

      dataField: 'talk_about',
      label: { text: '谈资建议' },
      editorType: 'dxEditor'
    }];

    formItems['params'] = [{
      itemType: 'group',
      colCount: 2,
      items: [{
        dataField: 'chateau_id',
        label: { text: '品牌' },
        validationRules: [{ type: "required" }],
        editorType: 'dxSelectBox',
        editorOptions: {
          dataSource: $.crudStore(API('restful?_model=wine-chateau')),
          showClearButton: true,
          placeholder: "品牌",
          searchEnabled: true,
          valueExpr: 'id',
          noDataText: '没有请求到品牌数据',
          itemTemplate: function itemTemplate(data, index, $el) {
            if (data) {
              $("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
            }
          },
          displayExpr: function displayExpr(data) {
            return data ? data.chname + " (" + data.name + ")" : "";
          }
        }

      }]
    }, {
      itemType: 'group',
      items: [{
        dataField: 'chname',
        validationRules: [{
          type: "required",
          message: "请输入商品名称"
        }],
        label: { text: '商品名称' }
      }, {
        dataField: 'name',
        validationRules: [{
          type: "required",
          message: "商品毛重"
        }],
        label: { text: '商品毛重' }
      }, {
        dataField: 'letDrink_recom',
        validationRules: [{
          type: "required",
          message: "请输入乐饮推荐语"
        }],
        label: { text: '商品毛重' }
      }]
    }, {
      itemType: 'group',
      colCount: 3,
      items: [{
        dataField: 'promotion_price',
        validationRules: [{ type: "required" }],
        label: { text: '促销价' },
        editorType: 'dxNumberBox'
      }, {
        dataField: 'price',
        validationRules: [{ type: "required" }],
        label: { text: '原价' },
        editorType: 'dxNumberBox'
      }, {
        dataField: 'sku',
        label: { text: '库存' },
        editorType: 'dxNumberBox'
      }]
    }, {
      itemType: 'group',
      colCount: 1,
      items: [{
        dataField: 'sell_method',
        validationRules: [{ type: "required" }],
        label: { text: '销售方式' },
        editorType: 'dxRadioGroup',
        editorOptions: {
          layout: "horizontal",
          valueExpr: 'value',
          dataSource: [{
            text: '线上销售',
            value: 'online'
          }, {
            text: '线下销售',
            value: 'offline'
          }, {
            text: '产品展示',
            value: 'show'
          }]
        },
        helpText: '线上销售可以从线上直接购买，前端的价格信息单独展示；线下销售，线上不能购买。价格展示在经销商信息上。'
      }]
    }, {
      itemType: 'group',
      items: [{
        dataField: 'banner',
        validationRules: [{
          type: "required"
        }],
        label: { text: '封面图' },
        editorType: 'ImageUploader',
        editorOptions: {
          single: true,
          imageWidth: 750,
          imageHeight: 422
        }
      }, {
        dataField: 'covers',
        validationRules: [{
          type: "required"
        }],
        label: { text: '轮播图' },
        editorType: 'ImageUploader',
        editorOptions: {
          imageWidth: 750,
          imageHeight: 1118
        }
      }]
    }, {
      itemType: 'group',
      colCount: '2',
      items: [{
        dataField: 'category',
        label: { text: '类别' },
        validationRules: [{
          type: "required",
          message: "请输入类别"
        }],
        editorType: 'dxSelectBox',
        editorOptions: {
          dataSource: prefetchData['product-category'],
          acceptCustomValue: true,
          onCustomItemCreating: function onCustomItemCreating(e) {
            return e.text;
          },
          placeholder: '选择或者输入类别'
        }
      }, {
        dataField: 'level',
        label: { text: '产品级别' }
      }]
    }, {
      dataField: 'vintage',
      label: { text: '生产日期' },
      validationRules: [{
        type: "required",
        message: "请输入生产日期"
      }],
      editorType: 'YearSelect'
    }, {
      itemType: 'group',
      items: [{
        dataField: 'importers',
        label: { text: '进口商' },
        editorType: 'dxTagBox',
        editorOptions: {
          deferRendering: false,
          dataSource: $.crudStore(API("restful?_model=sys-importer")),
          searchEnabled: true,
          valueExpr: 'id',
          displayExpr: 'name'
        }
      }, {
        dataField: 'dealers',
        label: { text: '经销商' },
        editorType: 'DealerInput',
        editorOptions: {}
      }]
    }];

    var tabs = [{
      text: '属性信息',
      id: "show"
    }, {
      text: "参数信息",
      id: "params",
      disabled: !id
    }];

    $.each(["params", "show"], function (index, item) {
      formInstances[item] = $("<div>").appendTo($("#wine-form")).dxForm({
        items: formItems[item],
        showColonAfterLabel: true,
        showValidationSummary: false,
        validationGroup: "crud",
        alignItemLabels: true,
        alignItemLabelsInAllGroups: true
      }).dxForm("instance");
    });

    function showTab(item) {
      for (var k in formInstances) {
        formInstances[k].option('visible', k === item);
      }
    }

    $("#dxtabs").dxTabs({
      dataSource: tabs,
      selectedIndex: 0,
      onItemClick: function onItemClick(e) {
        showTab(e.itemData.id);
      }
    });

    showTab("show");

    if (id) {
      wineStore.byKey(id).then(function (resp) {
        console.log(resp);

        $.each(["country_id", "chateau_id"], function (i, item) {
          resp[item] = parseInt(resp[item]);
        });

        $.each(["relation_products", "relation_importers"], function (i, item) {
          if (resp[item]) resp[item] = $.map(resp[item], function (it) {
            return it.id;
          });
        });

        if (resp['relation_dealers']) {
          resp['dealers'] = $.map(resp['relation_dealers'], function (it) {
            return { id: it.id, show: it.pivot.show, name: it.name };
          });
        }

        var mapped = {
          "blend_deployment": "deployment_graperies",
          "scenes": "scene_ids",
          "cuisines": "wine_cuisines",
          "relation_importers": "importers",
          "judge.expert_judges": "judge.judge_arr",
          "score.expert_scores": "score.self_arr",
          "score.same_scores": "score.same_arr",
          "drink.tasteKeywords": "drink.keywords"
        };

        for (var k in mapped) {
          if (_.has(resp, k)) {
            _.set(resp, mapped[k], _.get(resp, k));
            _.unset(resp, k);
          }
        }

        console.log(resp);

        var dataBasic = $.extend({}, resp);
        $.each(["drink", "score", "judge", "technique"], function (i, item) {
          dataBasic[item] = undefined;
        });

        formInstances['basic'].option('formData', dataBasic);

        formInstances['drink'].option('formData', resp.drink);
        formInstances['judge'].option('formData', resp.judge);
        formInstances['technique'].option('formData', resp.technique);

        formInstances['score'].option('formData', resp.score);
      });
    } else {
      var productData = new DevExpress.data.CustomStore({
        store: $.crudStore(wineStore)
      });

      //form(productData)
    }
  });

  function saveCurrentTab() {
    var selectedItem = $("#dxtabs").dxTabs("option", "selectedItem");

    if (selectedItem) {
      $("#saveData").dxButton('option', { disabled: true, text: '正在保存' });

      var url = selectedItem.id === 'basic' ? API("restful?_model=wine-product") : API("restful?_model=wine-product-" + selectedItem.id);

      var _formData = $.extend({}, formInstances[selectedItem.id].option('formData'));

      if (selectedItem.id !== 'basic') {
        _formData.product_id = id;
      } else {
        var mapped = {
          relation_products: 'product_relation_ids'
          //scenes: 'scene_ids'
        };

        for (var k in mapped) {
          if (_formData[k]) {
            _formData[mapped[k]] = _formData[k].join(",");
          } else {
            _formData[mapped[k]] = '';
          }

          _formData[k] = undefined;
        }

        if (_formData['covers']) {
          _formData['cover_ids'] = $.map(_formData['covers'], function (item) {
            return item.id;
          }).join(",");
        }
      }

      console.log(_formData);

      var request = null;
      if (_formData.id) {
        request = $.crudStore(url).update(_formData.id, _formData);
      } else {
        request = $.crudStore(url).insert(_formData);
      }

      request.then(function (resp, data) {

        DevExpress.ui.notify({
          message: "已更新"
        }, "success", 1000);

        if (!id) {
          _app.App.getEventContext().redirect('#/newproduct/' + data.data.id);
        }

        console.log(resp);
      }).fail(function (e) {

        var message = "更新失败";
        if ($.crudStoreResp && $.crudStoreResp.message) {
          message += ": " + $.crudStoreResp.message;
        } else {
          message += ": 服务器错误";
        }

        DevExpress.ui.notify({
          message: message
        }, "error", 1000);
      }).always(function () {
        $("#saveData").dxButton('option', { disabled: false, text: '保存' });
      });
    }
  }

  $("#saveData").dxButton({
    text: id ? '保存' : '新建',
    type: 'default',
    useSubmitBehavior: false
  }).click(function () {
    var selectedItem = $("#dxtabs").dxTabs("option", "selectedItem");

    if (selectedItem) {
      var result = formInstances[selectedItem.id].validate();

      if (!result.isValid) {
        var $el = result.validators[0].element();

        var offset = $el.offset();

        $('html, body').animate({
          scrollTop: offset.top - $("header.app-header").height() - 20
        });

        // } else if (validateForm(formInstances[selectedItem.id])) {
        //   saveCurrentTab();
      } else {
        saveCurrentTab();
      }
    }

    return false;
  });

  $("#cancel").dxButton({
    text: "返回",
    type: "normal",
    onClick: function onClick() {
      context.redirect("#/members");
    }
  });
};

_app.App.registerRoute({
  name: 'newproduct/:id',
  onLoad: function onLoad(context, $container) {
    initPage(context, $container);
  }
});

_app.App.registerRoute({
  name: 'newproduct',
  onLoad: function onLoad(context, $container) {
    initPage(context, $container);
  }
});


},{"./app":2,"./dx-ext":6,"./page":8,"./util":11}],10:[function(require,module,exports){
'use strict';

var _app = require('./app');

var _util = require('./util');

var _util2 = _interopRequireDefault(_util);

var _page = require('./page');

require('./dx-ext');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }


},{"./app":2,"./dx-ext":6,"./page":8,"./util":11}],11:[function(require,module,exports){
'use strict';

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Util = function () {
	function Util() {
		_classCallCheck(this, Util);
	}

	_createClass(Util, [{
		key: 'formatXbm',
		value: function formatXbm(xbm) {
			if (xbm == '2') return '女';else if (xbm == '1') return '男';else return xbm;
		}
	}, {
		key: 'crudStore',
		value: function crudStore(url, options) {

			var SERVICE_URL = url;
			options = $.extend({
				onDataArrived: function onDataArrived(data) {
					return data;
				}
			}, options);

			return new DevExpress.data.CustomStore($.extend({}, options, {

				load: function load(loadOptions) {

					var u = new Url(SERVICE_URL);

					u.query._param = JSON.stringify(loadOptions);

					return $.getJSON(u).then(function (resp) {
						console.log("data done");
						return options.onDataArrived(resp);
					});
				},

				byKey: function byKey(key) {
					var u = new Url(SERVICE_URL);
					u.path += "/" + encodeURIComponent(key);

					return $.getJSON(u).then(function (resp) {
						return resp;
					});
				},

				insert: function insert(values) {
					console.log(values);
					return $.post(SERVICE_URL, values).always(function (resp) {
						$.crudStoreResp = resp.responseJSON;
						return resp;
					});
				},

				update: function update(key, values) {
					var u = new Url(SERVICE_URL);
					u.path += "/" + encodeURIComponent(key);

					return $.ajax({
						url: u,
						method: "PUT",
						data: values
					}).always(function (resp) {
						$.crudStoreResp = resp.responseJSON;
						return resp;
					});
				},

				remove: function remove(key) {
					var u = new Url(SERVICE_URL);
					u.path += "/" + encodeURIComponent(key);

					return $.ajax({
						url: u,
						method: "DELETE"
					});
				}

			}));
		}
	}]);

	return Util;
}();

exports.default = new Util();


},{}]},{},[1]);
